// @tensorflow/tfjs Copyright 2019 Google
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.tf=t.tf||{})}(this,function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return(r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function i(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})}function o(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=e.call(t,a)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var a={},s={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function u(t){t in a||(a[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=document.createElement("canvas");return e.addEventListener("webglcontextlost",function(e){e.preventDefault(),delete a[t]},!1),1===t?e.getContext("webgl",s)||e.getContext("experimental-webgl",s):e.getContext("webgl2",s)}(t));var e=a[t];return e.isContextLost()?(delete a[t],u(t)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),a[t])}function l(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function c(t,e,n){return Math.max(t,Math.min(e,n))}function p(t){return t%2==0?t:t+1}function h(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function f(t,e){var n=Math.random();return e*n+(1-n)*t}function d(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function m(t,e,n){void 0===n&&(n=""),d(b(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})}function g(t){d(null!=t,function(){return"The input to the tensor constructor must be a non-null value."})}function y(t,e){if(void 0===e&&(e=[]),null==e&&(e=[]),Array.isArray(t)||_(t))for(var n=0;n<t.length;++n)y(t[n],e);else e.push(t);return e}function v(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function b(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function w(t){return t%1==0}function x(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)}function N(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function S(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function C(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise(function(r,i){var o=0,a=function(){if(t())r();else{var s=e(++o);null!=n&&o>=n?i():setTimeout(a,s)}};a()})}function E(t,e){for(var n=1,r=-1,i=0;i<t.length;++i)if(t[i]>=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var o=t.slice();return o[r]=e/n,o}function I(t,e){var n=e.length;return d((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&t<n}),function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t}),d(t.every(function(t){return w(t)}),function(){return"All values in axis param must be integers but got axis "+t}),t.map(function(t){return t<0?n+t:t})}function k(t,e){for(var n=[],r=[],i=null==e?null:I(e,t).sort(),o=0,a=0;a<t.length;++a){if(null!=i){if(i[o]===a&&1!==t[a])throw new Error("Can't squeeze axis "+a+" since its dim '"+t[a]+"' is not 1");(null==i[o]||i[o]>a)&&1===t[a]&&(n.push(t[a]),r.push(a)),i[o]<=a&&o++}1!==t[a]&&(n.push(t[a]),r.push(a))}return{newShape:n,keptDims:r}}function A(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function T(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function R(t,e,n){if("float32"===e)for(var r=0;r<t.length;r++){var i=t[r];if(isNaN(i)||!isFinite(i))throw Error("The result of the '"+n+"' is "+i+".")}}function D(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function O(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)}function _(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function M(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)}function L(t){if(null==t)return 0;var e=0;return t.forEach(function(t){return e+=2*t.length}),e}function F(t){return"string"==typeof t||t instanceof String}function z(t){return"boolean"==typeof t}function P(t){return"number"==typeof t}function B(t){return Array.isArray(t)?B(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":P(t)?"float32":F(t)?"string":z(t)?"bool":"float32"}function U(t){return!!(t&&t.constructor&&t.call&&t.apply)}function W(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function V(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}function j(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=y(t)),n&&D(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),i=0;i<r.length;++i)0!==Math.round(t[i])&&(r[i]=1);return r}throw new Error("Unknown data type "+e)}function q(t,e){if(0===t.length)return e[0];var n=t.reduce(function(t,e){return t*e});if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var i=new Array;if(1===n.length)for(var o=n[0],a=0;a<o;a++)i[a]=r[e+a];else{o=n[0];var s=n.slice(1),u=s.reduce(function(t,e){return t*e});for(a=0;a<o;a++)i[a]=t(e+a*u,s,r)}return i}(0,t,e)}function G(t,e){for(var n=H(t,e),r=0;r<n.length;r++)n[r]=1;return n}function H(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}function K(){if("undefined"!=typeof performance)return performance.now();if("undefined"!=typeof process){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}throw new Error("Cannot measure time in this environment. You should run tf.js in the browser or in Node.js")}function $(t){t.forEach(function(e){d(Number.isInteger(e)&&e>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}var X=Object.freeze({shuffle:l,clamp:c,nearestLargerEven:p,sum:h,randUniform:f,distSquared:function(t,e){for(var n=0,r=0;r<t.length;r++){var i=Number(t[r])-Number(e[r]);n+=i*i}return n},assert:d,assertShapesMatch:m,assertNonNull:g,flatten:y,sizeFromShape:v,isScalarShape:function(t){return 0===t.length},arraysEqual:b,isInt:w,tanh:x,sizeToSquarishShape:N,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return l(e),e},rightPad:S,repeatedTry:C,inferFromImplicitShape:E,parseAxisParam:I,squeezeShape:k,getTypedArrayFromDType:A,getArrayFromDType:T,checkComputationForErrors:R,checkConversionForErrors:D,hasEncodingLoss:O,isTypedArray:_,bytesPerElement:M,bytesFromStringArray:L,isString:F,isBoolean:z,isNumber:P,inferDtype:B,isFunction:U,nearestDivisor:W,computeStrides:V,toTypedArray:j,toNestedArray:q,makeOnesTypedArray:G,makeZerosTypedArray:H,now:K,assertNonNegativeIntegerDimensions:$}),Y=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new J)}return t.prototype.profileKernel=function(t,e){var n,r=this,i=this.backendTimer.time(function(){n=e()});return(Array.isArray(n)?n:[n]).forEach(function(e){var n=e.dataSync();R(n,e.dtype,t),i.then(function(i){var o="";null!=i.getExtraProfileInfo&&(o=i.getExtraProfileInfo()),r.logger.logKernelProfile(t,e,n,i.kernelMs,o)})}),n},t}(),J=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,i){var o=S(r+"ms",9),a=S(t,25),s=e.rank,u=e.size,l=S(e.shape.toString(),14);console.log("%c"+a+"\t%c"+o+"\t%c"+s+"D "+l+"\t%c"+u+"\t%c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green")},t}(),Z=20,Q=3,tt=7;function et(t,e,n,r){var i=V(e),o=function(t,e,n,r){var i=v(e),o=r[r.length-1],a=new Array(o).fill(0),s=e.length,u="complex64"===n?it(t):t;if(s>1)for(var l=0;l<i/o;l++)for(var c=l*o,p=0;p<o;p++)a[p]=Math.max(a[p],nt(u[c+p],0,n).length);return a}(t,e,n,i),a=e.length,s=function t(e,n,r,i,o,a){void 0===a&&(a=!0);var s="complex64"===r?2:1,u=n[0],l=n.length;if(0===l)return"complex64"===r?[nt(it(e)[0],0,r)]:"bool"===r?[rt(e[0])]:[e[0].toString()];if(1===l){if(u>Z){var c=Q*s,p=Array.from(e.slice(0,c)),h=Array.from(e.slice(u-Q*s,u));return"complex64"===r&&(p=it(p),h=it(h)),["["+p.map(function(t,e){return nt(t,o[e],r)}).join(", ")+", ..., "+h.map(function(t,e){return nt(t,o[u-Q+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?it(e):Array.from(e)).map(function(t,e){return nt(t,o[e],r)}).join(", ")+"]"]}var f=n.slice(1),d=i.slice(1),m=i[0]*s,g=[];if(u>Z){for(var y=0;y<Q;y++){var v=(b=y*m)+m;g.push.apply(g,t(e.slice(b,v),f,r,d,o,!1))}for(g.push("..."),y=u-Q;y<u;y++)v=(b=y*m)+m,g.push.apply(g,t(e.slice(b,v),f,r,d,o,y===u-1))}else for(y=0;y<u;y++){var b;v=(b=y*m)+m,g.push.apply(g,t(e.slice(b,v),f,r,d,o,y===u-1))}var w=2===l?",":"";g[0]="["+g[0]+w;for(y=1;y<g.length-1;y++)g[y]=" "+g[y]+w;var x=",\n";for(y=2;y<l;y++)x+="\n";return g[g.length-1]=" "+g[g.length-1]+"]"+(a?"":x),g}(t,e,n,i,o),u=["Tensor"];return r&&(u.push("  dtype: "+n),u.push("  rank: "+a),u.push("  shape: ["+e+"]"),u.push("  values:")),u.push(s.map(function(t){return"    "+t}).join("\n")),u.join("\n")}function nt(t,e,n){return S(Array.isArray(t)?parseFloat(t[0].toFixed(tt))+" + "+parseFloat(t[1].toFixed(tt))+"j":F(t)?"'"+t+"'":"bool"===n?rt(t):parseFloat(t.toFixed(tt)).toString(),e)}function rt(t){return 0===t?"false":"true"}function it(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var ot=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=v(t),null!=n){var i=n.length;d(i===this.size,function(){return"Length of values '"+i+"' does not match the size inferred by the shape '"+r.size+"'."})}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||T(e,this.size),this.strides=V(t)}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),d(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"});var i=this.locToIndex(n);this.values[i]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=t[t.length-1],r=0;r<t.length-1;++r)n+=this.strides[r]*t[r];return this.values[n]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return lt.make(this.shape,{values:this.values},this.dtype)},t}(),at=null,st=null,ut=null;var lt=function(){function t(t,e,n,r,i){this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=v(t),this.strides=V(t),this.dataId=null!=r?r:{},this.id=at().nextTensorId(),this.rankType=this.rank<5?this.rank.toString():"higher",at().registerTensor(this,i),null!=n&&at().write(this.dataId,n)}return t.make=function(e,n,r,i){return new t(e,r,n.values,n.dataId,i)},t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),d(1===this.size,function(){return"The array must have only 1 element."}),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,i){return this.throwIfDisposed(),this.reshape([t,e,n,r,i])},t.prototype.asType=function(t){return this.throwIfDisposed(),st.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return i(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,st.buffer(this.shape,this.dtype,t)]}})})},t.prototype.bufferSync=function(){return st.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return i(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,q(this.shape,t)]}})})},t.prototype.arraySync=function(){return q(this.shape,this.dataSync())},t.prototype.data=function(){return i(this,void 0,void 0,function(){return o(this,function(t){return this.throwIfDisposed(),[2,at().read(this.dataId)]})})},t.prototype.dataSync=function(){return this.throwIfDisposed(),at().readSync(this.dataId)},t.prototype.dispose=function(){this.isDisposed||(at().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},t.prototype.toFloat=function(){return this.asType("float32")},t.prototype.toInt=function(){return this.asType("int32")},t.prototype.toBool=function(){return this.asType("bool")},t.prototype.print=function(t){return void 0===t&&(t=!1),st.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),st.reshape(this,t)},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},t.prototype.expandDims=function(t){return void 0===t&&(t=0),st.expandDims(this,t)},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),st.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),st.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),st.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),st.oneHot(this,t,e,n)},t.prototype.toString=function(t){return void 0===t&&(t=!1),et(this.dataSync(),this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),st.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),st.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),st.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),st.dot(this,t)},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),st.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),st.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),st.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),st.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),st.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),st.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),st.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,i){return void 0===n&&(n=.001),ut("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,i,r,n)},t.prototype.batchNorm=function(t,e,n,r,i){return void 0===i&&(i=.001),this.throwIfDisposed(),st.batchNorm(this,t,e,n,r,i)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),st.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),st.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),st.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),st.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),st.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),st.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),st.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),st.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),st.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),st.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),st.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),st.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),st.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),st.div(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),st.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),st.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),st.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),st.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),st.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),st.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),st.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),st.modStrict(this,t)},t.prototype.squaredDifference=function(t){return this.throwIfDisposed(),st.squaredDifference(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),st.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),st.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),st.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),st.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),st.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),st.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),st.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),st.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),st.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),st.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),st.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),st.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),st.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),st.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),st.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),st.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),st.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),st.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),st.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),st.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),st.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),st.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),st.sign(this)},t.prototype.exp=function(){return this.throwIfDisposed(),st.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),st.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),st.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),st.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),st.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),st.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),st.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),st.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),st.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),st.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),st.relu(this)},t.prototype.elu=function(){return this.throwIfDisposed(),st.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),st.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),st.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),st.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),st.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),st.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),st.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),st.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),st.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),st.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),st.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),st.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),st.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),st.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),st.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),st.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),st.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),st.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),st.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),st.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),st.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),st.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),st.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),st.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),st.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),st.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),st.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),st.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,i,o){return void 0===r&&(r="NWC"),void 0===i&&(i=1),this.throwIfDisposed(),st.conv1d(this,t,e,n,r,i,o)},t.prototype.conv2d=function(t,e,n,r,i,o){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),st.conv2d(this,t,e,n,r,i,o)},t.prototype.conv2dTranspose=function(t,e,n,r,i){return this.throwIfDisposed(),st.conv2dTranspose(this,t,e,n,r,i)},t.prototype.depthwiseConv2D=function(t,e,n,r,i,o){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),st.depthwiseConv2d(this,t,e,n,r,i,o)},t.prototype.separableConv2d=function(t,e,n,r,i,o){return void 0===i&&(i=[1,1]),void 0===o&&(o="NHWC"),this.throwIfDisposed(),st.separableConv2d(this,t,e,n,r,i,o)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),st.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),st.maxPool(this,t,e,n,r)},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),st.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,i){return this.throwIfDisposed(),st.pool(this,t,e,n,r,i)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),ct.variable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),st.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),st.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),st.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),st.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,i,o,a,s){return void 0===r&&(r=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===s&&(s=0),this.throwIfDisposed(),st.stridedSlice(this,t,e,n,r,i,o,a,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),st.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),st.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),st.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),st.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),st.spectral.irfft(this)},t}();Object.defineProperty(lt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var ct=function(t){function e(e,n,r){void 0===n&&(n=!0);var i=t.call(this,e.shape,e.dtype,null,e.dataId)||this;i.trainable=n,i.name=r,null==i.name&&(i.name=at().nextVariableId().toString());try{at().registerVariable(i)}catch(t){throw at().disposeTensor(i),t}return i}return n(e,t),e.variable=function(t,n,r,i){return void 0===n&&(n=!0),null!=i&&i!==t.dtype&&(t=t.asType(i)),new e(t,n,r)},e.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!b(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");at().disposeTensor(this),this.dataId=t.dataId,at().registerTensor(this)},e}(lt);Object.defineProperty(ct,Symbol.hasInstance,{value:function(t){return t instanceof lt&&null!=t.assign&&t.assign instanceof Function}});var pt,ht,ft,dt,mt,gt=ct.variable;(mt=t.Rank||(t.Rank={})).R0="R0",mt.R1="R1",mt.R2="R2",mt.R3="R3",mt.R4="R4",mt.R5="R5",mt.R6="R6",function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(pt||(pt={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(ht||(ht={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(ft||(ft={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(dt||(dt={}));var yt={float32:ft,int32:pt,bool:ht,complex64:dt};function vt(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return yt[t][e]}function bt(t){return vt(t,"int32")}function wt(t,e){if(t.dtype===e.dtype)return[t,e];var n=vt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function xt(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof lt)n.push(e);else if(function(t){return Array.isArray(t)||"object"==typeof t}(e)){var i=e;for(var o in i){var a=i[o];r.has(a)||(r.add(a),t(a,n,r))}}}(t,e,new Set),e}var Nt,St=function(){function t(t,e,n){this.backend=t,this.safeMode=e,this.debugMode=n,this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.profiling=!1,this.gradientScopeCount=0,this.customGradientDepth=0,this.scopeStack=[],this.keepTensors=new Set,this.tensorInfo=new WeakMap,this.profiler=new Y(t),this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return t.prototype.moveData=function(t){this.write(t,this.readSync(t))},t.prototype.tidy=function(t,e,n){var r=this;void 0===n&&(n=!1);var i,o=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=t}return this.scopedRun(function(){return r.startScope(o,n)},function(){return r.endScope(i,n)},function(){return(i=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),i})},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},t.prototype.nextTensorId=function(){return t.nextTensorId++},t.prototype.nextVariableId=function(){return t.nextVariableId++},t.prototype.runKernel=function(t,e,n){var r,i=this,o=[],a=function(t){return o.push(t),t},s=null!=this.activeScope?this.activeScope.name:"",u=this.numBytes,l=this.numTensors;if(this.scopedRun(function(){return i.customGradientDepth++},function(){return i.customGradientDepth--},function(){r=i.debugMode()?i.profiler.profileKernel(s,function(){return t(i.backend,a)}):t(i.backend,a)}),this.shouldRecord()){var c={id:this.nextTapeNodeId++,name:s,inputs:e,outputs:Array.isArray(r)?r:[r]};null!=n&&(c.gradient=function(t){return n(t,o)}),this.activeTape.push(c)}return this.profiling&&this.activeProfile.kernels.push({name:s,bytesAdded:this.numBytes-u,totalBytesSnapshot:this.numBytes,tensorsAdded:this.numTensors-l,totalTensorsSnapshot:this.numTensors,inputShapes:Object.keys(e).map(function(t){return e[t].shape}),outputShape:Array.isArray(r)?r.map(function(t){return t.shape}):r.shape}),r},t.prototype.registerTensor=function(t,e){var n=this.tensorInfo.has(t.dataId)?this.tensorInfo.get(t.dataId).refCount:0;if(this.numTensors++,"string"===t.dtype&&this.numStringTensors++,0===n){this.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*M(t.dtype)),this.tensorInfo.set(t.dataId,{backend:null!=e?e:this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.numBytes+=r,null!=e?e.register(t.dataId,t.shape,t.dtype):this.backend.register(t.dataId,t.shape,t.dtype)}this.tensorInfo.get(t.dataId).refCount++,t instanceof ct||this.track(t)},t.prototype.registerVariable=function(t){if(null!=this.registeredVariables[t.name])throw new Error("Variable with name "+t.name+" was already registered");this.registeredVariables[t.name]=t},t.prototype.disposeTensor=function(t){if(this.tensorInfo.has(t.dataId)){this.keepTensors.has(t.id)&&this.keepTensors.delete(t.id),this.numTensors--,"string"===t.dtype&&this.numStringTensors--;var e=this.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.numBytes-=e.bytes),this.numDataBuffers--,e.backend.disposeData(t.dataId),this.tensorInfo.delete(t.dataId)):this.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.registeredVariables){var e=this.registeredVariables[t];this.disposeTensor(e),delete this.registeredVariables[t]}},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.numTensors,t.numDataBuffers=this.numDataBuffers,t.numBytes=this.numBytes,this.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return i(this,void 0,void 0,function(){var e,n;return o(this,function(r){return this.profiling=!0,e=this.numBytes,n=this.numTensors,this.activeProfile.kernels=[],this.activeProfile.result=t(),this.profiling=!1,this.activeProfile.peakBytes=Math.max.apply(Math,this.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.activeProfile.newBytes=this.numBytes-e,this.activeProfile.newTensors=this.numTensors-n,[2,this.activeProfile]})})},t.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t});var i={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e={};return n(t).forEach(function(t,n){e[n]=function(){return t}}),e}};this.activeTape.push(i)},t.prototype.keep=function(t){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {...}) to avoid memory leaks.");return this.keepTensors.add(t.id),t},t.prototype.startScope=function(t,e){void 0===e&&(e=!1),e&&0===this.gradientScopeCount&&(this.activeTape=[]),e&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};t&&(n.name=t),this.scopeStack.push(n),this.activeScope=n},t.prototype.endScope=function(t,e){var n=this;void 0===e&&(e=!1),e&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),i=xt(t);i.forEach(function(t){return r.add(t.id)});for(var o=0;o<this.activeScope.track.length;o++){var a=this.activeScope.track[o];r.has(a.id)||(null!=this.activeTape?i.push(a):a.dispose())}var s=this.scopeStack.pop();this.activeScope=0===this.scopeStack.length?null:this.scopeStack[this.scopeStack.length-1],i.forEach(function(t){!n.keepTensors.has(t.id)&&function(t,e){for(var n=0;n<e.length;n++)if(e[n].id===t.id)return!0;return!1}(t,s.track)&&n.track(t)})},t.prototype.gradients=function(t,e,n,r){var i=this;if(void 0===r&&(r=!1),d(e.length>0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");return this.tidy("gradients",function(){var o=t();d(o instanceof lt,function(){return"The result y returned by f() must be a tensor."});var a=function(t,e,n){for(var r={},i={},o=0;o<e.length;o++)r[e[o].id]=!0;for(o=0;o<t.length;o++){var a=(d=t[o]).inputs;for(var s in a){for(var u=a[s],l=!1,c=0;c<e.length;c++)if(r[u.id]){d.outputs.forEach(function(t){return r[t.id]=!0}),l=!0,i[d.id]=!0;break}if(l)break}}var p={};p[n.id]=!0;var h={};for(o=t.length-1;o>=0;o--)for(a=(d=t[o]).inputs,c=0;c<d.outputs.length;c++)if(p[d.outputs[c].id]){for(var s in a)p[a[s].id]=!0,h[d.id]=!0;break}var f=[];for(o=0;o<t.length;o++){var d;if(i[(d=t[o]).id]&&h[d.id]){var m={};for(var s in d.inputs){var g=d.inputs[s];r[g.id]&&(m[s]=g)}var y=Object.assign({},d);y.inputs=m,y.outputs=d.outputs,f.push(y)}}return f}(i.activeTape,e,o);if(!r&&0===a.length&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");var s={};return s[o.id]=null==n?function(t){var e=G(v(t),"float32");return lt.make(t,{values:e})}(o.shape):n,function(t,e){for(var n=function(n){var r=e[n],i=[];if(r.outputs.forEach(function(e){var n=t[e.id];if(null!=n)i.push(n);else{var r=lt.make(e.shape,{values:H(e.size,e.dtype)},e.dtype);i.push(r)}}),null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var o=r.gradient(1===r.outputs.length?i[0]:i);for(var a in r.inputs){if(!(a in o))throw new Error("Cannot backprop through input "+a+". Available gradients found: "+Object.keys(o)+".");var s=o[a]();if("float32"!==s.dtype)throw new Error("Error in gradient for op "+r.name+". The gradient of input "+a+" must have 'float32' dtype, but has '"+s.dtype+"'");var u=r.inputs[a];if(!b(s.shape,u.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+a+"' has shape '"+s.shape+"', which does not match the shape of the input '"+u.shape+"'");if(null==t[u.id])t[u.id]=s;else{var l=t[u.id];t[u.id]=l.add(s),l.dispose()}}},r=e.length-1;r>=0;r--)n(r)}(s,a),{value:o,grads:e.map(function(t){return s[t.id]})}},!0)},t.prototype.customGrad=function(t){var e=this;return d(U(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r,i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];return d(i.every(function(t){return t instanceof lt}),function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"}),e.scopedRun(function(){return e.customGradientDepth++},function(){return e.customGradientDepth--},function(){r=e.tidy(t.name,function(){var e=t.apply(void 0,i),r=e.value,o=e.gradFunc;return d(r instanceof lt,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"}),d(U(o),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."}),n=o,r},!0)}),e.shouldRecord()&&e.addTapeNode(i,r,function(t){var e=n(t),r=Array.isArray(e)?e:[e];return d(r.length===i.length,function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."}),d(r.every(function(t){return t instanceof lt}),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."}),r}),r}},t.prototype.write=function(t,e){var n=this.tensorInfo.get(t);if("string"===n.dtype){var r=L(e);this.numBytes+=r-n.bytes,n.bytes=r}this.backend!==n.backend&&(n.backend.disposeData(t),n.backend=this.backend,this.backend.register(t,n.shape,n.dtype)),this.backend.write(t,e)},t.prototype.readSync=function(t){return this.tensorInfo.get(t).backend.readSync(t)},t.prototype.read=function(t){return this.tensorInfo.get(t).backend.read(t)},t.prototype.fromPixels=function(t,e){return this.backend.fromPixels(t,e)},t.prototype.time=function(t){return i(this,void 0,void 0,function(){var e,n;return o(this,function(r){switch(r.label){case 0:return e=K(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=K()-e,[2,n]}})})},t.prototype.track=function(t){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {op();...}); to avoid memory leaks.");return null!=this.activeScope&&this.activeScope.track.push(t),t},t.nextTensorId=0,t.nextVariableId=0,t}();!function(t){t[t.NUMBER=0]="NUMBER",t[t.BOOLEAN=1]="BOOLEAN",t[t.STRING=2]="STRING"}(Nt||(Nt={}));var Ct,Et,It=[{name:"DEBUG",type:Nt.BOOLEAN},{name:"IS_BROWSER",type:Nt.BOOLEAN},{name:"WEBGL_LAZILY_UNPACK",type:Nt.BOOLEAN},{name:"WEBGL_CPU_FORWARD",type:Nt.BOOLEAN},{name:"WEBGL_PACK",type:Nt.BOOLEAN},{name:"WEBGL_PACK_BATCHNORMALIZATION",type:Nt.BOOLEAN},{name:"WEBGL_PACK_CLIP",type:Nt.BOOLEAN},{name:"WEBGL_PACK_DEPTHWISECONV",type:Nt.BOOLEAN},{name:"WEBGL_PACK_BINARY_OPERATIONS",type:Nt.BOOLEAN},{name:"WEBGL_PACK_ARRAY_OPERATIONS",type:Nt.BOOLEAN},{name:"WEBGL_PACK_IMAGE_OPERATIONS",type:Nt.BOOLEAN},{name:"WEBGL_PACK_REDUCE",type:Nt.BOOLEAN},{name:"WEBGL_CONV_IM2COL",type:Nt.BOOLEAN},{name:"WEBGL_MAX_TEXTURE_SIZE",type:Nt.NUMBER},{name:"WEBGL_NUM_MB_BEFORE_PAGING",type:Nt.NUMBER},{name:"WEBGL_MAX_TEXTURES_IN_SHADER",type:Nt.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:Nt.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:Nt.BOOLEAN},{name:"WEBGL_VERSION",type:Nt.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:Nt.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:Nt.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:Nt.BOOLEAN},{name:"WEBGL_SIZE_UPLOAD_UNIFORM",type:Nt.NUMBER},{name:"BACKEND",type:Nt.STRING},{name:"EPSILON",type:Nt.NUMBER},{name:"PROD",type:Nt.BOOLEAN},{name:"TENSORLIKE_CHECK_SHAPE_CONSISTENCY",type:Nt.BOOLEAN},{name:"DEPRECATION_WARNINGS_ENABLED",type:Nt.BOOLEAN}];function kt(t){try{if(null!=u(t))return!0}catch(t){return!1}return!1}var At="tfjsflags";function Tt(){var t={};if("undefined"==typeof window||void 0===window.location||void 0===window.location.search)return t;var e=function(t){var e={};return t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];return function(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}(e,n[0],n[1]),n.join("=")}),e}(window.location.search);if(At in e){var n={};e[At].split(",").forEach(function(t){var e=t.split(":"),r=e[0],i=e[1];n[r]=i}),It.forEach(function(e){e.name in n&&(console.log("Setting feature override from URL "+e.name+": "+n[e.name]),e.type===Nt.NUMBER?t[e.name]=+n[e.name]:e.type===Nt.BOOLEAN?t[e.name]="true"===n[e.name]:e.type===Nt.STRING?t[e.name]=n[e.name]:console.warn("Unknown URL param: "+e.name+"."))})}return t}function Rt(t,e){return null!=t.getExtension(e)}function Dt(t,e){var n=t.createFramebuffer(),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);var i=2===e?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,i,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var o=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(n),o}var Ot=600;var _t,Mt=function(){function t(t){this.features={},this.registry={},null!=t&&(this.features=t),this.get("DEBUG")&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}return t.setBackend=function(t,e){if(void 0===e&&(e=!1),!(t in Ut.registry))throw new Error("Backend name '"+t+"' not found in registry");Ut.engine.backend=Ut.findBackend(t),Ut.backendName=t},t.getBackend=function(){return Ut.initEngine(),Ut.backendName},t.disposeVariables=function(){Ut.engine.disposeVariables()},t.memory=function(){return Ut.engine.memory()},t.profile=function(t){return Ut.engine.profile(t)},t.tidy=function(t,e){return Ut.engine.tidy(t,e)},t.dispose=function(t){xt(t).forEach(function(t){return t.dispose()})},t.keep=function(t){return Ut.engine.keep(t)},t.time=function(t){return Ut.engine.time(t)},t.prototype.get=function(t){return t in this.features?this.features[t]:(this.features[t]=this.evaluateFeature(t),this.features[t])},t.prototype.getFeatures=function(){return this.features},t.prototype.set=function(t,e){this.features[t]=e},t.prototype.getBestBackendName=function(){var t=this;if(0===Object.keys(this.registry).length)throw new Error("No backend found in registry.");return Object.keys(this.registry).map(function(e){return{name:e,entry:t.registry[e]}}).sort(function(t,e){return e.entry.priority-t.entry.priority})[0].name},t.prototype.evaluateFeature=function(t){if("DEBUG"===t)return!1;if("IS_BROWSER"===t)return"undefined"!=typeof window;if("IS_NODE"===t)return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node;if("IS_CHROME"===t)return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor);if("WEBGL_CPU_FORWARD"===t)return!0;if("WEBGL_PACK"===t)return 0!==this.get("WEBGL_VERSION");if("WEBGL_PACK_BATCHNORMALIZATION"===t)return this.get("WEBGL_PACK");if("WEBGL_PACK_CLIP"===t)return this.get("WEBGL_PACK");if("WEBGL_PACK_DEPTHWISECONV"===t)return this.get("WEBGL_PACK");if("WEBGL_PACK_BINARY_OPERATIONS"===t)return this.get("WEBGL_PACK");if("WEBGL_PACK_ARRAY_OPERATIONS"===t)return this.get("WEBGL_PACK");if("WEBGL_PACK_IMAGE_OPERATIONS"===t)return this.get("WEBGL_PACK");if("WEBGL_PACK_REDUCE"===t)return this.get("WEBGL_PACK");if("WEBGL_LAZILY_UNPACK"===t)return this.get("WEBGL_PACK");if("WEBGL_CONV_IM2COL"===t)return this.get("WEBGL_PACK");if("WEBGL_NUM_MB_BEFORE_PAGING"===t)return this.get("PROD")||!this.get("IS_BROWSER")?Number.POSITIVE_INFINITY:window.screen.height*window.screen.width*window.devicePixelRatio*Ot/1024;if("WEBGL_MAX_TEXTURE_SIZE"===t)return function(t){if(null==Ct){var e=u(t);Ct=e.getParameter(e.MAX_TEXTURE_SIZE)}return Ct}(this.get("WEBGL_VERSION"));if("WEBGL_MAX_TEXTURES_IN_SHADER"===t)return function(t){if(null==Et){var e=u(t);Et=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Et)}(this.get("WEBGL_VERSION"));if("IS_TEST"===t)return!1;if("BACKEND"===t)return this.getBestBackendName();if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"===t){var e=this.get("WEBGL_VERSION");return 0===e?0:function(t){if(0===t)return 0;var e=u(t);return Rt(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Rt(e,"EXT_disjoint_timer_query")?1:0}(e)}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===t)return this.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!function(){var t=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}();if("HAS_WEBGL"===t)return this.get("WEBGL_VERSION")>0;if("WEBGL_VERSION"===t)return kt(2)?2:kt(1)?1:0;if("WEBGL_RENDER_FLOAT32_ENABLED"===t)return function(t){if(0===t)return!1;var e=u(t);if(1===t){if(!Rt(e,"OES_texture_float"))return!1}else if(!Rt(e,"EXT_color_buffer_float"))return!1;return Dt(e,t)}(this.get("WEBGL_VERSION"));if("WEBGL_DOWNLOAD_FLOAT_ENABLED"===t)return function(t){if(0===t)return!1;var e=u(t);if(1===t){if(!Rt(e,"OES_texture_float"))return!1;if(!Rt(e,"WEBGL_color_buffer_float"))return!1}else if(!Rt(e,"EXT_color_buffer_float"))return!1;return Dt(e,t)}(this.get("WEBGL_VERSION"));if("WEBGL_FENCE_API_ENABLED"===t)return function(t){return 2===t&&null!=u(t).fenceSync}(this.get("WEBGL_VERSION"));if("WEBGL_SIZE_UPLOAD_UNIFORM"===t)return this.get("WEBGL_RENDER_FLOAT32_ENABLED")?4:0;if("TEST_EPSILON"===t)return 32===this.backend.floatPrecision()?.001:.1;if("EPSILON"===t)return 32===this.backend.floatPrecision()?1e-7:1e-4;if("PROD"===t)return!1;if("TENSORLIKE_CHECK_SHAPE_CONSISTENCY"===t)return!this.get("PROD");if("DEPRECATION_WARNINGS_ENABLED"===t)return!0;throw new Error("Unknown feature "+t+".")},t.prototype.setFeatures=function(t){this.features=Object.assign({},t)},t.prototype.reset=function(){this.features=Tt(),null!=this.globalEngine&&(this.globalEngine=null)},Object.defineProperty(t.prototype,"backend",{get:function(){return this.engine.backend},enumerable:!0,configurable:!0}),t.prototype.findBackend=function(t){return t in this.registry?this.registry[t].backend:null},t.prototype.registerBackend=function(t,e,n){var r=this;if(void 0===n&&(n=1),t in this.registry)return console.warn(t+" backend was already registered. Reusing existing backend"),!1;try{var i=e();return i.setDataMover({moveData:function(t){return r.engine.moveData(t)}}),this.registry[t]={backend:i,priority:n},!0}catch(e){return console.warn("Registration of backend "+t+" failed"),console.warn(e.stack||e.message),!1}},t.prototype.removeBackend=function(t){if(!(t in this.registry))throw new Error(t+" backend not found in registry");this.registry[t].backend.dispose(),delete this.registry[t]},Object.defineProperty(t.prototype,"engine",{get:function(){return this.initEngine(),this.globalEngine},enumerable:!0,configurable:!0}),t.prototype.initEngine=function(){var t=this;if(null==this.globalEngine){this.backendName=this.get("BACKEND");var e=this.findBackend(this.backendName);this.globalEngine=new St(e,!1,function(){return t.get("DEBUG")})}},Object.defineProperty(t.prototype,"global",{get:function(){return Lt()},enumerable:!0,configurable:!0}),t}();function Lt(){if(null==_t){var t=void 0;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof global)t=global;else{if("undefined"==typeof process)throw new Error("Could not find a global object");t=process}_t=t}return _t}function Ft(){Ut.set("PROD",!0)}function zt(){Ut.set("DEBUG",!0)}function Pt(){Ut.set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Bt(t){Ut.get("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}!function(t){ut=t}(Bt);var Ut=function(){var t=Lt();return null==t.ENV&&(t.ENV=new Mt(Tt())),function(t){at=t}(function(){return t.ENV.engine}),t.ENV}(),Wt=Object.freeze({EPSILON_FLOAT16:1e-4,EPSILON_FLOAT32:1e-7,Environment:Mt,enableProdMode:Ft,enableDebugMode:zt,disableDeprecationWarnings:Pt,deprecationWarn:Bt,ENV:Ut});function Vt(t,e){if(d(U(t),function(){return"The f passed in variableGrads(f) must be a function"}),d(null==e||Array.isArray(e)&&e.every(function(t){return t instanceof ct}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"}),null==e)for(var n in e=[],Ut.engine.registeredVariables)e.push(Ut.engine.registeredVariables[n]);var r=e.length;d((e=e.filter(function(t){return t.trainable})).length>0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+r+" variables is trainable."});var i=Ut.engine.gradients(t,e,null,!0),o=i.value,a=i.grads;d(a.some(function(t){return null!=t}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),d(0===o.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+o.rank+" tensor"});var s={};return e.forEach(function(t,e){null!=a[e]&&(s[t.name]=a[e])}),{value:o,grads:s}}function jt(t){return Ut.engine.customGrad(t)}function qt(t){if(t.filter(function(t){return null==t}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n    the f you passed encloses all operations that lead from x to y.")}var Gt=Mt.tidy,Ht=Mt.keep,Kt=Mt.dispose,$t=Mt.time,Xt=Mt.profile;function Yt(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Ut.get("IS_TEST")||console.warn.apply(console,t)}function Jt(t,e,n,r){void 0===r&&(r=!0);var i=[];if(r)(i=i.concat(e.slice(0))).push(t[0]/n),i=i.concat(t.slice(1));else{i=i.concat(t[0]);for(var o=e.length,a=0;a<o;++a)i=i.concat([t[a+1]/e[a],e[a]]);i=i.concat(t.slice(o+1))}return i}function Zt(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var i=e+1;i<t;++i)i<=2*e?(r.push(i),r.push(i-(e+1))):r.push(i)}else{var o=[],a=[];for(i=1;i<t;++i)i>=2*e+1||i%2==1?a.push(i):o.push(i);r.push.apply(r,o),r.push(0),r.push.apply(r,a)}return r}function Qt(t,e,n,r){void 0===r&&(r=!0);var i=[];r?i.push(t[0]/n):i.push(t[0]*n);for(var o=1;o<t.length;++o)o<=e.length?r?i.push(e[o-1]*t[o]):i.push(t[o]/e[o-1]):i.push(t[o]);return i}function te(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function ee(t,e,n){for(var r=t.slice(0,1),i=0;i<n;++i)r.push(t[i+1]-e[i][0]-e[i][1]);return r}function ne(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function re(t,e){for(var n=[],r=t.length,i=0;i<r;i++)-1===e.indexOf(i)&&n.push(t[i]);return[n,e.map(function(e){return t[e]})]}function ie(t,e){return function(t,e,n){for(var r=t.length+e.length,i=[],o=0,a=0,s=0;s<r;s++)-1===n.indexOf(s)?i.push(t[o++]):i.push(e[a++]);return i}(t,e.map(function(t){return 1}),e)}function oe(t,e,n){d(ne(e,n),function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."})}function ae(t,e){if(ne(t,e))return null;for(var n=[],r=0;r<e;++r)-1===t.indexOf(r)&&n.push(r);return t.forEach(function(t){return n.push(t)}),n}function se(t){return t.map(function(t,e){return[e,t]}).sort(function(t,e){return t[1]-e[1]}).map(function(t){return t[0]})}function ue(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function le(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function ce(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],i=1,o=0;o<n.length-1;++o)i*=n[o];var a=t.shape,s=n.slice();s.pop();var u=1;for(o=r;o<t.rank;++o)u*=a[o],s.push(a[o]);var l=V(t.shape).map(function(t){return t/u}).concat([1]).slice(0,r);return[s,i,u,l]}var pe=30;function he(t){return t<=pe?t:W(t,Math.floor(Math.sqrt(t)))}function fe(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,i=e.rank>1?e.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+i+".";if(n.rank<i)throw new Error(o+" update.rank < "+i+". ");if(t.length<r+(n.rank-i))throw new Error(o+" Output shape length < "+(r+(n.rank-i)));if(n.rank!==i+t.length-r)throw new Error(o+" update.rank != "+(i+t.length-r));for(var a=0;a<i;++a)if(n.shape[a]!==e.shape[a])throw new Error(o+" updates.shape["+a+"] ("+n.shape[a]+") != indices.shape["+a+"] ("+e.shape[a]+").");for(a=0;a<n.rank-i;++a)if(n.shape[a+i]!==t[a+r])throw new Error(o+" updates.shape["+(a+i)+"] ("+n.shape[a+i]+") != shape["+(a+i)+"] ("+t[a+i]+")")}(n,e,t)}function de(t,e,n){for(var r=e.rank>1?e.shape[e.rank-1]:1,i=n.length,o=1,a=r;a<i;++a)o*=n[a];var s=r<1?1:r;return{sliceRank:r,numUpdates:e.size/s,sliceSize:o,strides:V(n.slice(0,r)).concat([1]),outputSize:v(n)}}function me(t,e,n,r,i,o,a,s,u){if(void 0===i&&(i=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===s&&(s=0),void 0===u&&(u=0),0!==a)throw new Error("ellipsis mask is not yet supported");if(0!==s)throw new Error("new axis mask is not yet supported");for(var l=[],c=[],p=[],h=0;h<t.length;h++)l[h]=ge(i,e,r,t,h),c[h]=ye(o,n,r,t,h),u&1<<h&&(c[h]=l[h]+1,p.push(h));var f=new Array(t.length).fill(0);return f=f.map(function(t,e){for(var n=0,i=l[e];!(r[e]>0?i>=c[e]:i<=c[e]);i+=r[e])n+=1;return n}),[l,f,p]}function ge(t,e,n,r,i){var o=e[i];t&1<<i&&(o=n[i]>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var a=r[i];return o<0&&(o+=a),c(0,o,a-1)}function ye(t,e,n,r,i){var o=e[i];t&1<<i&&(o=n[i]>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var a=r[i];return o<0&&(o+=a),n[i]>0?c(0,o,a):c(-1,o,a-1)}function ve(t,e,n){for(var r=n.length,i=0;i<n.length;i++)if(n[i]>1){r=i;break}for(i=r+1;i<n.length;i++)if(e[i]>0||n[i]!==t[i])return!1;return!0}function be(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}function we(t){var e=t;if(_(t))return[t.length];if(!Array.isArray(t))return[];for(var n=[];Array.isArray(e)||_(e);)n.push(e.length),e=e[0];return Array.isArray(t)&&Ut.get("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],Array.isArray(e)||_(e)){d(n.length>0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),d(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var i=n.slice(1),o=0;o<e.length;++o)t(e[o],i,r.concat(o))}else d(0===n.length,function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"})}(t,n,[]),n}function xe(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor")}function Ne(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof lt)return xe(r,t.dtype,e,n),t;var i=B(t);if("string"!==i&&["bool","int32","float32"].indexOf(r)>=0&&(i=r),xe(r,i,e,n),!_(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+t.constructor.name+"'");var o=we(t);_(t)||Array.isArray(t)||(t=[t]);var a="string"!==i?j(t,i,Ut.get("DEBUG")):y(t);return lt.make(o,{values:a},i)}function Se(t,e,n){if(!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return Ne(t,e+"["+r+"]",n)})}function Ce(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var i=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Ut.engine.startScope(n);try{var i=r.apply(void 0,t);return i instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Ut.engine.endScope(i),i}catch(t){throw Ut.engine.endScope(null),t}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}var Ee=Ce({softmax_:function(t,e){void 0===e&&(e=-1);var n=Ne(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return jt(function(t){var n=t.logSumExp([e],!0),r=t.toFloat().sub(n).exp();return{value:r,gradFunc:function(t){var n=t.mul(r);return n.sub(n.sum([e],!0).mul(r))}}})(n)}}),Ie=Ce({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=Ne(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return jt(function(t){var n=t.max(e,!0),r=t.sub(n),i=r.toFloat().sub(r.exp().sum(e,!0).log());return{value:i,gradFunc:function(t){var n=i.exp();return t.sub(t.sum(e,!0).mul(n))}}})(n)}});var ke=Ce({complex_:function(t,e){var n=Ne(t,"real","complex"),r=Ne(e,"imag","complex");return m(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Ut.engine.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),Ae=Ce({real_:function(t){var e=Ne(t,"input","real");return Ut.engine.runKernel(function(t){return t.real(e)},{$input:e})}}),Te=Ce({imag_:function(t){var e=Ne(t,"input","imag");return Ut.engine.runKernel(function(t){return t.imag(e)},{$input:e})}});function Re(t,e,n){if(null==n&&(n=B(t)),"complex64"===n)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!_(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");var r=we(t);if(null!=e){$(e);var i=v(e),o=v(r);d(i===o,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+i+" values but has "+o});for(var a=0;a<r.length;++a){var s=r[a],u=a!==r.length-1||s!==v(e.slice(a));d(r[a]===e[a]||!u,function(){return"Error creating a new Tensor. Inferred shape ("+r+") does not match the provided shape ("+e+"). "})}}return _(t)||Array.isArray(t)||(t=[t]),e=e||r,t="string"!==n?j(t,n,Ut.get("DEBUG")):y(t),lt.make(e,{values:t},n)}function De(t,e){if((_(t)||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");return Re(t,[],e)}function Oe(t,e){g(t);var n=we(t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Re(t,n,e)}function _e(t,e,n){if(g(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=we(t);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Re(t,e=e||r,n)}function Me(t,e,n){if(g(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=we(t);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Re(t,e=e||r,n)}function Le(t,e,n){if(g(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=we(t);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Re(t,e=e||r,n)}function Fe(t,e,n){if(g(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=we(t);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Re(t,e=e||r,n)}function ze(t,e,n){if(g(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=we(t);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Re(t,e=e||r,n)}function Pe(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Pe(t,"float32"),r=Pe(t,"float32");return ke(n,r)}var i=G(v(t),e);return lt.make(t,{values:i},e)}function Be(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Be(t,"float32"),r=Be(t,"float32");return ke(n,r)}var i=H(v(t),e);return lt.make(t,{values:i},e)}function Ue(t,e,n){return Ut.engine.runKernel(function(r){return r.fill(t,e,n)},{})}function We(t,e,n){if(0===n)throw new Error("Cannot request zero samples");var r=(e-t)/(n-1),i=H(n,"float32");i[0]=t;for(var o=1;o<i.length;o++)i[o]=i[o-1]+r;return Oe(i,"float32")}function Ve(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return Be([0],r);var i=H(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),i[0]=t;for(var o=1;o<i.length;o++)i[o]=i[o-1]+n;return Oe(i,r)}var je=Ce({onesLike_:function(t){var e=Ne(t,"x","onesLike");return Ut.engine.runKernel(function(t){return t.onesLike(e)},{$x:e},null)}}),qe=Ce({zerosLike_:function(t){var e=Ne(t,"x","zerosLike");return Ut.engine.runKernel(function(t){return t.zerosLike(e)},{$x:e},null)}}),Ge=function(){function t(t){this.dataMover=t,this.data=new WeakMap}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(t),this.data.get(t)},t.prototype.set=function(t,e){this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.data.delete(t)},t}(),He=function(){function t(){}return t.prototype.time=function(t){throw new Error("Not yet implemented.")},t.prototype.read=function(t){throw new Error("Not yet implemented.")},t.prototype.readSync=function(t){throw new Error("Not yet implemented.")},t.prototype.disposeData=function(t){throw new Error("Not yet implemented.")},t.prototype.write=function(t,e){throw new Error("Not yet implemented.")},t.prototype.fromPixels=function(t,e){throw new Error("Not yet implemented.")},t.prototype.register=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.memory=function(){throw new Error("Not yet implemented.")},t.prototype.floatPrecision=function(){throw new Error("Not yet implemented")},t.prototype.batchMatMul=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fusedBatchMatMul=function(t,e,n,r,i,o){throw new Error("Not yet implemented")},t.prototype.slice=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.stridedSlice=function(t,e,n,r,i,o,a,s,u){throw new Error("Not yet implemented")},t.prototype.unstack=function(t,e){throw new Error("Not yet implemented")},t.prototype.reverse=function(t,e){throw new Error("Not yet implemented")},t.prototype.concat=function(t,e){throw new Error("Not yet implemented")},t.prototype.neg=function(t){throw new Error("Not yet implemented")},t.prototype.add=function(t,e){throw new Error("Not yet implemented")},t.prototype.addN=function(t){throw new Error("Not yet implemented")},t.prototype.subtract=function(t,e){throw new Error("Not yet implemented")},t.prototype.multiply=function(t,e){throw new Error("Not yet implemented")},t.prototype.realDivide=function(t,e){throw new Error("Not yet implemented")},t.prototype.floorDiv=function(t,e){throw new Error("Not yet implemented")},t.prototype.sum=function(t,e){throw new Error("Not yet implemented")},t.prototype.prod=function(t,e){throw new Error("Not yet implemented")},t.prototype.unsortedSegmentSum=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.argMin=function(t,e){throw new Error("Not yet implemented")},t.prototype.argMax=function(t,e){throw new Error("Not yet implemented")},t.prototype.equal=function(t,e){throw new Error("Not yet implemented")},t.prototype.notEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.less=function(t,e){throw new Error("Not yet implemented")},t.prototype.lessEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.greater=function(t,e){throw new Error("Not yet implemented")},t.prototype.greaterEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalNot=function(t){throw new Error("Not yet implemented")},t.prototype.logicalAnd=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalOr=function(t,e){throw new Error("Not yet implemented")},t.prototype.where=function(t){throw new Error("Not yet implemented")},t.prototype.select=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.topk=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.min=function(t,e){throw new Error("Not yet implemented")},t.prototype.minimum=function(t,e){throw new Error("Not yet implemented")},t.prototype.mod=function(t,e){throw new Error("Not yet implemented")},t.prototype.max=function(t,e){throw new Error("Not yet implemented")},t.prototype.maximum=function(t,e){throw new Error("Not yet implemented")},t.prototype.all=function(t,e){throw new Error("Not yet implemented")},t.prototype.any=function(t,e){throw new Error("Not yet implemented")},t.prototype.squaredDifference=function(t,e){throw new Error("Not yet implemented")},t.prototype.ceil=function(t){throw new Error("Not yet implemented")},t.prototype.floor=function(t){throw new Error("Not yet implemented")},t.prototype.round=function(t){throw new Error("Not yet implemented")},t.prototype.sign=function(t){throw new Error("Not yet implemented")},t.prototype.pow=function(t,e){throw new Error("Not yet implemented")},t.prototype.exp=function(t){throw new Error("Not yet implemented")},t.prototype.expm1=function(t){throw new Error("Not yet implemented")},t.prototype.log=function(t){throw new Error("Not yet implemented")},t.prototype.log1p=function(t){throw new Error("Not yet implemented")},t.prototype.sqrt=function(t){throw new Error("Not yet implemented")},t.prototype.rsqrt=function(t){throw new Error("Not yet implemented")},t.prototype.square=function(t){throw new Error("Not yet implemented")},t.prototype.reciprocal=function(t){throw new Error("Not yet implemented")},t.prototype.relu=function(t){throw new Error("Not yet implemented")},t.prototype.prelu=function(t,e){throw new Error("Not yet implemented")},t.prototype.elu=function(t){throw new Error("Not yet implemented")},t.prototype.eluDer=function(t,e){throw new Error("Not yet implemented")},t.prototype.selu=function(t){throw new Error("Not yet implemented")},t.prototype.int=function(t){throw new Error("Not yet implemented")},t.prototype.clip=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.abs=function(t){throw new Error("Not yet implemented")},t.prototype.complexAbs=function(t){throw new Error("Not yet implemented")},t.prototype.sigmoid=function(t){throw new Error("Not yet implemented")},t.prototype.softplus=function(t){throw new Error("Not yet implemented")},t.prototype.sin=function(t){throw new Error("Not yet implemented")},t.prototype.cos=function(t){throw new Error("Not yet implemented")},t.prototype.tan=function(t){throw new Error("Not yet implemented")},t.prototype.asin=function(t){throw new Error("Not yet implemented")},t.prototype.acos=function(t){throw new Error("Not yet implemented")},t.prototype.atan=function(t){throw new Error("Not yet implemented")},t.prototype.atan2=function(t,e){throw new Error("Not yet implemented")},t.prototype.sinh=function(t){throw new Error("Not yet implemented")},t.prototype.cosh=function(t){throw new Error("Not yet implemented")},t.prototype.tanh=function(t){throw new Error("Not yet implemented")},t.prototype.asinh=function(t){throw new Error("Not yet implemented")},t.prototype.acosh=function(t){throw new Error("Not yet implemented")},t.prototype.atanh=function(t){throw new Error("Not yet implemented")},t.prototype.erf=function(t){throw new Error("Not yet implemented")},t.prototype.step=function(t,e){throw new Error("Not yet implemented")},t.prototype.conv2d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2D=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPoolBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.avgPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPoolBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.reshape=function(t,e){throw new Error("Not yet implemented")},t.prototype.cast=function(t,e){throw new Error("Not yet implemented")},t.prototype.tile=function(t,e){throw new Error("Not yet implemented")},t.prototype.pad=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.transpose=function(t,e){throw new Error("Not yet implemented")},t.prototype.gather=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.gatherND=function(t,e){throw new Error("Not yet implemented")},t.prototype.scatterND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchToSpaceND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.spaceToBatchND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeBilinear=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeBilinearBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchNormalization=function(t,e,n,r,i,o){throw new Error("Not yet implemented")},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.LRNGrad=function(t,e,n,r,i,o,a){throw new Error("Not yet implemented")},t.prototype.multinomial=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.oneHot=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.cumsum=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.nonMaxSuppression=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.fft=function(t){throw new Error("Not yet implemented")},t.prototype.ifft=function(t){throw new Error("Not yet implemented")},t.prototype.complex=function(t,e){throw new Error("Not yet implemented")},t.prototype.real=function(t){throw new Error("Not yet implemented")},t.prototype.imag=function(t){throw new Error("Not yet implemented")},t.prototype.cropAndResize=function(t,e,n,r,i,o){throw new Error("Not yet implemented")},t.prototype.depthToSpace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.split=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.sparseToDense=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fill=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.onesLike=function(t){throw new Error("Not yet implemented")},t.prototype.zerosLike=function(t){throw new Error("Not yet implemented")},t.prototype.setDataMover=function(t){throw new Error("Not yet implemented")},t.prototype.dispose=function(){throw new Error("Not yet implemented")},t}();function Ke(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=Be(t.shape),i=t.toFloat(),o=n.complex(i,r);return r.dispose(),i.dispose(),o}if(!O(t.dtype,e))return lt.make(t.shape,{dataId:t.dataId},e);if("complex64"===t.dtype){var a=n.real(t);return o=a.cast(e),a.dispose(),o}if("int32"===e)return n.int(t);if("bool"===e){var s=De(0,t.dtype);return o=n.notEqual(t,s),s.dispose(),o}throw new Error("Error in Cast: unknown dtype argument ("+e+")")}function $e(t,e){return lt.make(e,{dataId:t.dataId},t.dtype)}function Xe(t,e){if(t.length!==e.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+t.length+", imag: "+e.length+".");for(var n=new Float32Array(2*t.length),r=0;r<n.length;r+=2)n[r]=t[r/2],n[r+1]=e[r/2];return n}function Ye(t,e){return{real:t[2*e],imag:t[2*e+1]}}function Je(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function Ze(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function Qe(t,e,n,r,i){for(var o=Array.from(e).map(function(t,e){return{score:t,boxIndex:e}}).filter(function(t){return t.score>i}).sort(function(t,e){return e.score-t.score}),a=[],s=0;s<o.length;s++){var u=o[s],l=u.score,c=u.boxIndex;if(l<i)break;for(var p=!1,h=a.length-1;h>=0;--h)if(tn(t,c,a[h])>=r){p=!0;break}if(!p&&(a.push(c),a.length>=n))break}return Oe(a,"int32")}function tn(t,e,n){var r=t.subarray(4*e,4*e+4),i=t.subarray(4*n,4*n+4),o=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(i[0],i[2]),c=Math.min(i[1],i[3]),p=Math.max(i[0],i[2]),h=Math.max(i[1],i[3]),f=(s-o)*(u-a),d=(p-l)*(h-c);if(f<=0||d<=0)return 0;var m=Math.max(o,l),g=Math.max(a,c),y=Math.min(s,p),v=Math.min(u,h),b=Math.max(y-m,0)*Math.max(v-g,0);return b/(f+d-b)}function en(t,e,n){var r=new Array(t.rank).fill(0),i=t.shape.slice();return e.map(function(e){i[n]=e;var o=t.slice(r,i);return r[n]+=e,o})}function nn(t,e,n,r,i){for(var o=e[e.length-1],a=[t.length/o,o],s=a[0],u=a[1],l=A(n,s*r),c=A("int32",s*r),p=0;p<s;p++){for(var h=p*u,f=t.subarray(h,h+u),d=[],m=0;m<f.length;m++)d.push({value:f[m],index:m});d.sort(function(t,e){return e.value-t.value});var g=p*r,y=l.subarray(g,g+r),v=c.subarray(g,g+r);for(m=0;m<r;m++)y[m]=d[m].value,v[m]=d[m].index}var b=e.slice();return b[b.length-1]=r,[Re(l,b,n),Re(c,b,"int32")]}var rn=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,i=t.batchSize,o=t.inSize,a=Math.ceil(o/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[i,a];var s="max"===e?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+r+";\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < "+r+"; i++) {\n          int inIdx = "+u+";\n          float candidate = getA(batch, inIdx);\n          if (candidate "+s+" bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    "};function on(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function an(t,e){return 1===e?[t]:on(t,e)}function sn(t,e){for(var n=t.length,r=[],i=0;i<n;i++){var o=n-1-i,a=t[o]||1;(e[e.length-1-i]||1)>1&&1===a&&r.unshift(o)}return r}function un(t,e){for(var n=[],r=0;r<e.length;r++){var i=t[t.length-r-1],o=e.length-r-1,a=e[o];(null==i||1===i&&a>1)&&n.unshift(o)}return n}function ln(t,e){for(var n=[],r=Math.max(t.length,e.length),i=0;i<r;i++){var o=t[t.length-i-1];null==o&&(o=1);var a=e[e.length-i-1];if(null==a&&(a=1),1===o)n.unshift(a);else if(1===a)n.unshift(o);else{if(o!==a)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(o)}}return n}function cn(){var t,e,n,r,i,o,a,s;return 2===Ut.get("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",i="texture",o="outputColor",a="out vec4 outputColor;",s="\n      #define round(value) newRound(value)\n      int newRound(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 newRound(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "):(t="",e="attribute",n="varying",r="varying",i="texture2D",o="gl_FragColor",a="",s="\n      int round(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 round(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:i,output:o,defineOutput:a,defineRound:s}}function pn(t,e,n){void 0===n&&(n="index");var r=V(e);return r.map(function(e,i){return"int "+t[i]+" = "+n+" / "+e+"; "+(i===r.length-1?"int "+t[i+1]+" = "+n+" - "+t[i]+" * "+e:"index -= "+t[i]+" * "+e)+";"}).join("")}function hn(t){return 1===t.length?""+t[0]:"vec"+t.length+"("+t.join(",")+")"}function fn(t,e,n,r){var i=[];t.forEach(function(t){var e=v(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?i.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(i.push("uniform sampler2D "+t.name+";"),i.push("uniform int offset"+t.name+";"))});var o,a,s=i.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?mn(t):dn(t);var i=t.shapeInfo.logicalShape,o=e.logicalShape;return i.length<=o.length&&(r+=n?function(t,e){var n,r=t.name,i=r.charAt(0).toUpperCase()+r.slice(1),o="get"+i+"AtOutCoords",a=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=sn(t.shapeInfo.logicalShape,e.logicalShape),l=Nn(s),c=s-a,p=["x","y","z","w","u","v"];n=0===a?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return"coords."+p[t+c]+" = 0;"}).join("\n");var h="";h=s<2&&a>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+c]}).join(", ");var f="return outputValue;";if(1===a&&s>1)f="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";else if(0===a&&s>0)f=1===s?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(u.length){var d=a-2,m=a-1;u.indexOf(d)>-1&&u.indexOf(m)>-1?f="return vec4(outputValue.x);":u.indexOf(d)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(m)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return"\n    vec4 "+o+"() {\n      "+l+" coords = getOutputCoords();\n      "+n+"\n      vec4 outputValue = get"+i+"("+h+");\n      "+f+"\n    }\n  "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),i="get"+r+"AtOutCoords",o=e.texShape,a=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&b(a,o))return"\n      float "+i+"() {\n        return sampleTexture("+n+", resultUV);\n      }\n    ";var l=Nn(u),c=sn(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n    float "+i+"() {\n      "+l+" coords = getOutputCoords();\n      "+(0===s?"":u<2&&c.length>=1?"coords = 0;":c.map(function(t){return"coords."+h[t+p]+" = 0;"}).join("\n"))+"\n      return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+p]}).join(", "))+");\n    }\n  "}(t,e)),r}(t,e,r)}).join("\n"),l=e.texShape,c=cn(),p=function(t){return"\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return "+t.texture2D+"(textureSampler, uv).r;\n    }\n  "}(c),h=function(t){var e="";return e=Ut.get("PROD")?"\n      bool isNaN(float val) {\n        return false;\n      }\n\n      bool hasNaN(vec4 values) {\n        return false;\n      }\n    ":"\n      bool isNaN(float val) {\n        return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n      }\n\n      bvec4 isNaN(vec4 val) {\n        return bvec4(\n          isNaN(val.x),\n          isNaN(val.y),\n          isNaN(val.z),\n          isNaN(val.w)\n        );\n      }\n\n      bool hasNaN(vec4 values) {\n        return any(bvec4(\n          isNaN(values.x),\n          isNaN(values.y),\n          isNaN(values.z),\n          isNaN(values.w)\n        ));\n      }\n    ",t.version+"\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    "+t.varyingFs+" vec2 resultUV;\n    "+t.defineOutput+"\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    "+e+"\n\n    float getNaN(vec4 values) {\n      return dot(vec4(1), values);\n    }\n\n    "+t.defineRound+"\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    //Based on the work of Dave Hoskins\n    //https://www.shadertoy.com/view/4djSRW\n    #define HASHSCALE1 443.8975\n    float random(float seed){\n      vec2 p = resultUV * seed;\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\n      p3 += dot(p3, p3.yzx + 19.19);\n      return fract((p3.x + p3.y) * p3.z);\n    }\n\n    "+gn+"\n    "+yn+"\n    "+vn+"\n  "}(c);return e.isPacked?(o=function(t,e){switch(t.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * "+n[1]+".0);\n      }\n    ":1===n[1]?"\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * "+n[0]+".0);\n      }\n    ":"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      return resTexRC.x * "+n[1]+" + resTexRC.y;\n    }\n  "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(b(t,e))return"\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n      }\n    ";var r=Math.ceil(t[1]/2);return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec2(r, c);\n    }\n  "}(t,e);case 3:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[2]/2),i=r*Math.ceil(t[1]/2);return"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n      int b = index / "+i+";\n      index -= b * "+i+";\n\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec3(b, r, c);\n    }\n  "}(t,e);default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),i=r*Math.ceil(t[t.length-2]/2),o=i,a="",s="b, r, c",u=2;u<t.length-1;u++)a="\n      int b"+u+" = index / "+(o*=t[t.length-u-1])+";\n      index -= b"+u+" * "+o+";\n    "+a,s="b"+u+", "+s;return"\n    ivec"+t.length+" getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n      "+a+"\n\n      int b = index / "+i+";\n      index -= b * "+i+";\n\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec"+t.length+"("+s+");\n    }\n  "}(t,e)}}(e.logicalShape,l),a=function(t){return"\n    void setOutput(vec4 val) {\n      "+t.output+" = val;\n    }\n  "}(c)):(o=function(t,e){switch(t.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(t,e){return 1===e[0]?"\n      int getOutputCoords() {\n        return int(resultUV.x * "+e[1]+".0);\n      }\n    ":1===e[1]?"\n      int getOutputCoords() {\n        return int(resultUV.y * "+e[0]+".0);\n      }\n    ":"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      return resTexRC.x * "+e[1]+" + resTexRC.y;\n    }\n  "}(0,e);case 2:return function(t,e){return b(t,e)?"\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n      }\n    ":1===t[1]?"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+e[0]+", "+e[1]+"));\n        int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    ":1===t[0]?"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+e[0]+", "+e[1]+"));\n        int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n        return ivec2(0, index);\n      }\n    ":"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      int r = index / "+t[1]+";\n      int c = index - r * "+t[1]+";\n      return ivec2(r, c);\n    }\n  "}(t,e);case 3:return function(t,e){var n=pn(["r","c","d"],t);return"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      "+n+"\n      return ivec3(r, c, d);\n    }\n  "}(t,e);case 4:return function(t,e){var n=pn(["r","c","d","d2"],t);return"\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      "+n+"\n      return ivec4(r, c, d, d2);\n    }\n  "}(t,e);case 5:return function(t,e){var n=pn(["r","c","d","d2","d3"],t);return"\n    ivec5 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2("+e[0]+",\n                             "+e[1]+"));\n\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n      "+n+"\n\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\n      return outShape;\n    }\n  "}(t,e);case 6:return function(t,e){var n=pn(["r","c","d","d2","d3","d4"],t);return"\n    ivec6 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n      "+n+"\n\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\n      return result;\n    }\n  "}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported")}}(e.logicalShape,l),a=function(t){return"\n    void setOutput(float val) {\n      "+t.output+" = vec4(val, 0, 0, 0);\n    }\n  "}(c)),r&&(h+=bn),[h,p,a,s,o,u,n].join("\n")}function dn(t){var e=t.shapeInfo.logicalShape;switch(e.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,i=r[0],o=r[1];if(1===i&&1===o)return"\n      float "+n+"() {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var a=t.shapeInfo.texShape;return"\n    float "+n+"() {\n      vec2 uv = uvFromFlat("+a[0]+", "+a[1]+", "+wn(e)+");\n      return sampleTexture("+e+", uv);\n    }\n  "}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n      float "+n+"(int index) {\n        "+xn(t)+"\n      }\n    ";var r=t.shapeInfo.texShape,i=r[0],o=r[1];if(1===o&&1===i)return"\n      float "+n+"(int index) {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var a=wn(e);return 1===o?"\n      float "+n+"(int index) {\n        vec2 uv = vec2(0.5, (float(index + "+a+") + 0.5) / "+i+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ":1===i?"\n      float "+n+"(int index) {\n        vec2 uv = vec2((float(index + "+a+") + 0.5) / "+o+".0, 0.5);\n        return sampleTexture("+e+", uv);\n      }\n    ":"\n    float "+n+"(int index) {\n      vec2 uv = uvFromFlat("+i+", "+o+", index + "+a+");\n      return sampleTexture("+e+", uv);\n    }\n  "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t.shapeInfo.texShape;if(null!=i&&b(e,i)){var o=i[0];return"\n    float "+r+"(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2("+i[1]+".0, "+o+".0);\n      return sampleTexture("+n+", uv);\n    }\n  "}var a=k(e),s=a.newShape,u=a.keptDims,l=s;if(l.length<e.length)return"\n      "+dn(Sn(t,l))+"\n      float "+r+"(int row, int col) {\n        return "+r+"("+Cn(["row","col"],u)+");\n      }\n    ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2("+e[1]+", 1)));\n        "+xn(t)+"\n      }\n    ";var c=i[0],p=i[1],h=wn(n);return 1===p?"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+h+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / "+c+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ":1===c?"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+h+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2((index + 0.5) / "+p+".0, 0.5);\n      return sampleTexture("+n+", uv);\n    }\n  ":"\n  float "+r+"(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * "+e[1]+" + col + "+h+";\n    vec2 uv = uvFromFlat("+c+", "+p+", index);\n    return sampleTexture("+n+", uv);\n  }\n"}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e[1]*e[2],o=e[2],a=k(e),s=a.newShape,u=a.keptDims,l=s;if(l.length<e.length)return"\n        "+dn(Sn(t,l))+"\n        float "+r+"(int row, int col, int depth) {\n          return "+r+"("+Cn(["row","col","depth"],u)+");\n        }\n      ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3("+i+", "+o+", 1)));\n        "+xn(t)+"\n      }\n    ";var c=t.shapeInfo.texShape,p=c[0],h=c[1],f=t.shapeInfo.flatOffset;return h===i&&null==f?"\n        float "+r+"(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2("+o+", 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2("+h+".0, "+p+".0);\n          return sampleTexture("+n+", uv);\n        }\n      ":h===o&&null==f?"\n    float "+r+"(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2("+e[1]+", 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+h+".0, "+p+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ":"\n      float "+r+"(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * "+i+" + col * "+o+" + depth + "+wn(n)+";\n        vec2 uv = uvFromFlat("+p+", "+h+", index);\n        return sampleTexture("+n+", uv);\n      }\n  "}(t);case 4:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e[3],o=e[2]*i,a=e[1]*o,s=k(e),u=s.newShape,l=s.keptDims;if(u.length<e.length)return"\n      "+dn(Sn(t,u))+"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        return "+r+"("+Cn(["row","col","depth","depth2"],l)+");\n      }\n    ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4("+a+", "+o+", "+i+", 1)));\n        "+xn(t)+"\n      }\n    ";var c=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,h=p[0],f=p[1];return f===a&&null==c?"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3("+o+", "+i+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+f+".0, "+h+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":f===i&&null==c?"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3("+e[1]*e[2]+", "+e[2]+", 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+f+".0, "+h+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":"\n    float "+r+"(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+a+" + col * "+o+" +\n          depth * "+i+" + depth2;\n      vec2 uv = uvFromFlat("+h+", "+f+", index + "+wn(n)+");\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);case 5:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e[4],o=e[3]*i,a=e[2]*o,s=e[1]*a,u=k(e),l=u.newShape,c=u.keptDims;if(l.length<e.length)return"\n      "+dn(Sn(t,l))+"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        return "+r+"("+Cn(["row","col","depth","depth2","depth3"],c)+");\n      }\n    ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+s+", "+a+", "+o+", "+i+")) +\n          depth3;\n        "+xn(t)+"\n      }\n    ";var p=t.shapeInfo.flatOffset,h=t.shapeInfo.texShape,f=h[0],d=h[1];return d===s&&null==p?"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n                         vec4("+a+", "+o+", "+i+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+d+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":d===i&&null==p?"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]+",\n               "+e[2]*e[3]+", "+e[3]+", 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+d+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":"\n    float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+s+" + col * "+a+" + depth * "+o+" +\n          depth2 * "+i+" + depth3 + "+wn(n)+";\n      vec2 uv = uvFromFlat("+f+", "+d+", index);\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);case 6:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=k(e),o=i.newShape,a=i.keptDims;if(o.length<e.length)return"\n      "+dn(Sn(t,o))+"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return "+r+"("+Cn(["row","col","depth","depth2","depth3","depth4"],a)+");\n      }\n    ";var s=e[5],u=e[4]*s,l=e[3]*u,c=e[2]*l,p=e[1]*c;if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n        int index = round(dot(\n          vec4(row, col, depth, depth2),\n          vec4("+p+", "+c+", "+l+", "+u+")) +\n          dot(\n            vec2(depth3, depth4),\n            vec2("+s+", 1)));\n        "+xn(t)+"\n      }\n    ";var h=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,d=f[0],m=f[1];return m===p&&null==h?"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n          vec4("+c+", "+l+", "+u+", "+s+")) +\n               float(depth4);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+m+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":m===s&&null==h?"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]*e[4]+",\n               "+e[2]*e[3]*e[4]+",\n               "+e[3]*e[4]+",\n               "+e[4]+")) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+m+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":"\n    float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+p+" + col * "+c+" + depth * "+l+" +\n          depth2 * "+u+" + depth3 * "+s+" + depth4 + "+wn(n)+";\n      vec2 uv = uvFromFlat("+d+", "+m+", index);\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);default:throw new Error(e.length+"-D input sampling is not yet supported")}}function mn(t){switch(t.shapeInfo.logicalShape.length){case 0:return function(t){var e=t.name;return"\n    vec4 get"+e.charAt(0).toUpperCase()+e.slice(1)+"() {\n      return "+cn().texture2D+"("+e+", halfCR);\n    }\n  "}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=cn();return"\n    vec4 "+n+"(int index) {\n      vec2 uv = packedUVfrom1D(\n        "+i[0]+", "+i[1]+", index);\n      return "+o.texture2D+"("+e+", uv);\n    }\n  "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t.shapeInfo.texShape,o=i[0],a=i[1],s=cn();if(null!=i&&b(e,i))return"\n      vec4 "+r+"(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2("+a+".0, "+o+".0);\n\n        return "+s.texture2D+"("+n+", uv);\n      }\n    ";var u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];return"\n    vec4 "+r+"(int row, int col) {\n      vec2 uv = packedUVfrom2D("+Math.ceil(e[1]/2)+", "+u[0]+", "+u[1]+", row, col);\n      return "+s.texture2D+"("+n+", uv);\n    }\n  "}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(1===e[0])return"\n        "+mn(Sn(t,e.slice(1)))+"\n        vec4 "+r+"(int b, int row, int col) {\n          return "+r+"("+Cn(["b","row","col"],[1,2])+");\n        }\n      ";var a=o[0],s=o[1],u=Math.ceil(e[2]/2);return"\n    vec4 "+r+"(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        "+a+", "+s+", "+u*Math.ceil(e[1]/2)+", "+u+", b, row, col);\n      return "+cn().texture2D+"("+n+", uv);\n    }\n  "}(t);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),o=t.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],s=a[0],u=a[1],l=Math.ceil(e[n-1]/2),c=l*Math.ceil(e[n-2]/2),p="int b, int row, int col",h="b * "+c+" + (row / 2) * "+l+" + (col / 2)",f=2;f<n-1;f++)p="int b"+f+", "+p,h="b"+f+" * "+(c*=e[n-f-1])+" + "+h;return"\n    vec4 "+i+"("+p+") {\n      int index = "+h+";\n      int texR = index / "+u+";\n      int texC = index - texR * "+u+";\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n      return "+cn().texture2D+"("+r+", uv);\n    }\n  "}(t)}}var gn="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n  int texelIndex = index / 2;\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",yn="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n  int texNumC, int row, int col) {\n  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",vn="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n    int texelsInBatch, int texelsInLogicalRow, int b,\n    int row, int col) {\n  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",bn="\n  float getChannel(vec4 frag, vec2 innerDims) {\n    vec2 modCoord = mod(innerDims, 2.);\n    return modCoord.x == 0. ?\n      (modCoord.y == 0. ? frag.r : frag.g) :\n      (modCoord.y == 0. ? frag.b : frag.a);\n  }\n  float getChannel(vec4 frag, int dim) {\n    float modCoord = mod(float(dim), 2.);\n    return modCoord == 0. ? frag.r : frag.g;\n  }\n";function wn(t){return"offset"+t}function xn(t){var e=t.name,n=v(t.shapeInfo.logicalShape);return 1===n?"return "+e+";":"\n    for (int i = 0; i < "+n+"; i++) {\n      if (i == index) {\n        return "+e+"[i];\n      }\n    }\n  "}function Nn(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported")}function Sn(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function Cn(t,e){return e.map(function(e){return t[e]}).join(", ")}var En=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,d(t.length>2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var i=t[t.length-1],o=Math.ceil(i/e);this.outputShape=t.slice(0,-1),o>1&&this.outputShape.push(o),r||this.variableNames.push("bestIndicesA");var a,s,u=this.outputShape,l=u.length,c=Nn(l),p=an("coords",l);if(1===o){var h=Nn(s=l+1);a="\n        "+h+" sourceLocR = "+h+"("+p.join()+", 0);\n        ++"+p[l-1]+";\n        "+h+" sourceLocG = "+h+"("+p.join()+", 0);\n        ++"+p[l-2]+";\n        "+h+" sourceLocA = "+h+"("+p.join()+", 0);\n        --"+p[l-1]+";\n        "+h+" sourceLocB = "+h+"("+p.join()+", 0);\n        --"+p[l-2]+";"}else s=l,a="\n        "+c+" sourceLocR = coords;\n        ++"+p[l-1]+";\n        "+c+" sourceLocG = coords;\n        ++"+p[l-2]+";\n        "+c+" sourceLocA = coords;\n        --"+p[l-1]+";\n        "+c+" sourceLocB = coords;\n        --"+p[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),m="."+f[s-1],g=f.map(function(t){return"int "+t}),y=an("sourceLocR",s-1).concat("inIdx.r"),v=an("sourceLocG",s-1).concat("inIdx.g"),b=an("sourceLocB",s-1).concat("inIdx.b"),w=an("sourceLocA",s-1).concat("inIdx.a"),x="max"===n?"greaterThan":"lessThan",N=r?"":"\n          inIdx = round(vec4(getBestIndicesAChannel("+y.join()+"),\n                             getBestIndicesAChannel("+v.join()+"),\n                             getBestIndicesAChannel("+b.join()+"),\n                             getBestIndicesAChannel("+w.join()+")));",S="vec4(\n            getAChannel("+y.join()+"),\n            hasNextCol ? getAChannel("+v.join()+") : 0.,\n            hasNextRow ? getAChannel("+b.join()+") : 0.,\n            hasNextRow && hasNextCol ? getAChannel("+w.join()+") : 0.)",C=r?"":"\n      float getBestIndicesAChannel("+g.join()+") {\n        return getChannel(getBestIndicesA("+f.join()+"),\n                                          vec2("+f.slice(-2).join()+"));\n      }";this.userCode="\n      float getAChannel("+g.join()+") {\n        return getChannel(getA("+f.join()+"),\n                               vec2("+f.slice(-2).join()+"));\n      }\n      "+C+"\n      void main() {\n        "+c+" coords = getOutputCoords();\n        bool hasNextCol = "+p[l-1]+" < "+(u[l-1]-1)+";\n        bool hasNextRow = "+p[l-2]+" < "+(u[l-2]-1)+";\n        "+a+"\n        ivec4 srcIdx = ivec4(sourceLocR"+m+", sourceLocG"+m+",\n          sourceLocB"+m+", sourceLocA"+m+") * "+e+";\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = "+S+";\n\n        for (int i = 0; i < "+e+"; i++) {\n          inIdx = srcIdx;\n          "+N+"\n          vec4 candidate = "+S+";\n          bvec4 nan = isNaN(candidate);\n          bvec4 replace = bvec4(\n            vec4("+x+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,\n                           replace.y  ? candidate.y : bestValue.y,\n                           replace.z  ? candidate.z : bestValue.z,\n                           replace.w  ? candidate.w : bestValue.w);\n          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n          srcIdx++;\n        }\n        setOutput(bestIndex);\n      }\n    "},In=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n      const ivec2 pads = ivec2("+l+", "+c+");\n      const float avgMultiplier = float("+p+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+s+";\n            wR += "+o+") {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+u+";\n            wC+= "+a+") {\n            float dyC = float(dyCCorner + wC) / "+i+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n\n            dotProd += dyValue * avgMultiplier;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},kn=function(t,e,n,r,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],ln(t,e),ln(t,n);var a="0.0";null!=r&&(ln(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="1.0";null!=i&&(ln(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = "+a+";\n        float scale = "+s+";\n        float inv = scale * inversesqrt(variance + float("+o+"));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    "},An=function(t,e,n,r,i,o){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],ln(t,e),ln(t,n);var a="vec4(0.0)";null!=r&&(ln(t,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=i&&(ln(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        vec4 offset = "+a+";\n        vec4 scale = "+s+";\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    "},Tn="return areal * breal - aimag * bimag;",Rn="return areal * bimag + aimag * breal;",Dn=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=ln(e,n),this.userCode="\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        "+t+"\n      }\n\n      void main() {\n        float areal = getARealAtOutCoords();\n        float aimag = getAImagAtOutCoords();\n        float breal = getBRealAtOutCoords();\n        float bimag = getBImagAtOutCoords();\n        setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n      }\n    "},On="return a + b;",_n="return a - b;",Mn="return a * b;",Ln=function(){function t(t,e,n){this.variableNames=["A","B"],this.outputShape=ln(e,n),this.userCode="\n      uniform float NAN;\n      float binaryOperation(float a, float b) {\n        "+t+"\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(){var t=this;return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"NAN"),null==t.startLoc)||e.gl.uniform1f(t.startLoc,NaN)}},t}(),Fn=function(){function t(t,e,n){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=ln(e,n),this.userCode="\n      uniform float NAN;\n      vec4 binaryOperation(vec4 a, vec4 b) {\n        "+t+"\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(){var t=this;return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"NAN"),null==t.startLoc)||e.gl.uniform1f(t.startLoc,NaN)}},t}(),zn=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n      uniform float min;\n      uniform float max;\n\n      void main() {\n        float value = getAAtOutCoords();\n        if (isNaN(value)) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, min, max));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"min"),n.maxLoc=r.getUniformLocationNoThrow(i,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Pn=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n      uniform float min;\n      uniform float max;\n\n      void main() {\n        vec4 value = getAAtOutCoords();\n\n        if (hasNaN(value)) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, vec4(min), vec4(max)));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"min"),n.maxLoc=r.getUniformLocationNoThrow(i,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Bn=function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n      void main() {\n        float re = abs(getRealAtOutCoords());\n        float im = abs(getImagAtOutCoords());\n        float mx = max(re, im);\n\n        // sadly the length function in glsl is not underflow-safe\n        // (at least not on Intel GPUs). So the safe solution is\n        // to ensure underflow-safety in all cases.\n        setOutput(\n          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n        );\n      }\n    "},Un=function(t){this.outputShape=[],this.outputShape=le(t,1),this.variableNames=t.map(function(t,e){return"T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var i=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+i+"));")}var o=e.length,a=e[e.length-1];r.push("else setOutput(getT"+o+"(yR, yC-"+a+"));"),this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        "+r.join("\n        ")+"\n      }\n    "},Wn=function(t,e){this.usesPackedTextures=!0,this.outputShape=[],this.outputShape=le(t,e);var n=this.outputShape,r=n.length,i=Nn(r),o=an("coords",r),a=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map(function(t,e){return"T"+e});var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u<s.length;u++)s[u]=s[u-1]+t[u][e];var l=a[e],c="vec2("+a.slice(-2).join()+")",p=a.join(),h="if ("+l+" < "+s[0]+")\n          return getChannel(getT0("+p+"), "+c+");";for(u=1;u<s.length;u++){var f=s[u-1];h+="\n        else if ("+l+" < "+s[u]+") {\n          "+l+" -= "+f+";\n          return getChannel(getT"+u+"("+p+"), "+c+");\n        }"}var d=s.length;h+="\n        else {\n          "+l+" -= "+s[s.length-1]+";\n          return getChannel(getT"+d+"("+p+"), "+c+");\n        }",this.userCode="\n      float getValue("+a.map(function(t){return"int "+t})+") {\n        "+h+"\n      }\n\n      void main() {\n        "+i+" coords = getOutputCoords();\n        vec4 result = vec4(getValue("+o+"), 0., 0., 0.);\n        if (++"+o[r-1]+" < "+n[r-1]+") {\n          result.g = getValue("+o+");\n        }\n        if (++"+o[r-2]+" < "+n[r-2]+") {\n          result.a = getValue("+o+");\n        }\n        if ("+o[r-2]+" < "+n[r-2]+" &&\n            --"+o[r-1]+" < "+n[r-1]+") {\n          result.b = getValue("+o+");\n        }\n        setOutput(result);\n      }\n    "},Vn=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int d2 = coords.w;\n\n        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n            int xR = wR + yR * "+e+" - "+r+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n              int xC = wC + yC * "+n+" - "+i+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},jn=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=e-1-t.padInfo.top,a=n-1-t.padInfo.left;this.userCode="\n      const ivec2 pads = ivec2("+o+", "+a+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+i+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n              float xValue = getDy(batch, idyR, idyC, d2);\n              float wValue = getW(wRPerm, wCPerm, d1, d2);\n              dotProd += xValue * wValue;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},qn=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.padInfo.front,o=t.padInfo.top,a=t.padInfo.left;this.userCode="\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int wF = coords.x;\n        int wR = coords.y;\n        int wC = coords.z;\n        int d1 = coords.w;\n        int d2 = coords.u;\n\n        float dotProd = 0.0;\n\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n            int xF = wF + yF * "+e+" - "+i+";\n\n            if (xF < 0 || xF >= "+t.inDepth+") {\n              continue;\n            }\n\n            for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n              int xR = wR + yR * "+n+" - "+o+";\n\n              if (xR < 0 || xR >= "+t.inHeight+") {\n                continue;\n              }\n\n              for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n                int xC = wC + yC * "+r+" - "+a+";\n\n                if (xC < 0 || xC >= "+t.inWidth+") {\n                  continue;\n                }\n\n                float dyValue = getDy(b, yF, yR, yC, d2);\n                float xValue = getX(b, xF, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Gn=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,o=t.strideHeight,a=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n      const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.u;\n\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyFCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+e+"; wF++) {\n          float dyF = float(dyFCorner + wF) / "+i+".0;\n\n          if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = "+e+" - 1 - wF;\n\n          for (int wR = 0; wR < "+n+"; wR++) {\n            float dyR = float(dyRCorner + wR) / "+o+".0;\n\n            if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n              fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            int wRPerm = "+n+" - 1 - wR;\n\n            for (int wC = 0; wC < "+r+"; wC++) {\n              float dyC = float(dyCCorner + wC) / "+a+".0;\n\n              if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              int wCPerm = "+r+" - 1 - wC;\n\n              for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n                float xValue = getDy(batch, idyF, idyR, idyC, d2);\n                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Hn=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.outChannels/t.inChannels;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int dm = coords.w;\n        int d2 = d1 * "+o+" + dm;\n\n        float dotProd = 0.0;\n\n        // TODO: Vec4 over the batch size\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n            int xR = wR + yR * "+e+" - "+r+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n              int xC = wC + yC * "+n+" - "+i+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Kn=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,o=e-1-t.padInfo.top,a=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n      const ivec2 pads = ivec2("+o+", "+a+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+i+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            // TODO: Vec4 over the channelMul\n            for (int dm = 0; dm < "+s+"; dm++) {\n              int d2 = d1 * "+s+" + dm;\n              float xValue = getDy(batch, idyR, idyC, d2);\n              float wValue = getW(wRPerm, wCPerm, d1, dm);\n              dotProd += xValue * wValue;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},$n=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.top,n=t.padInfo.left,r=t.strideHeight,i=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,s=t.filterHeight,u=t.filterWidth,l=4*Math.floor(t.inChannels/4),c=t.inChannels%4;this.userCode="\n      const ivec2 strides = ivec2("+r+", "+i+");\n      const ivec2 pads = ivec2("+e+", "+n+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+s+"; wR++) {\n          int xR = xRCorner + wR * "+o+";\n\n          if (xR < 0 || xR >= "+t.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+u+"; wC++) {\n            int xC = xCCorner + wC * "+a+";\n\n            if (xC < 0 || xC >= "+t.inWidth+") {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < "+l+"; d1 += 4) {\n              vec4 xValues = vec4(\n                getX(batch, xR, xC, d1),\n                getX(batch, xR, xC, d1 + 1),\n                getX(batch, xR, xC, d1 + 2),\n                getX(batch, xR, xC, d1 + 3)\n              );\n              vec4 wValues = vec4(\n                getW(wR, wC, d1, d2),\n                getW(wR, wC, d1 + 1, d2),\n                getW(wR, wC, d1 + 2, d2),\n                getW(wR, wC, d1 + 3, d2)\n              );\n\n              dotProd += dot(xValues, wValues);\n            }\n\n            if ("+(1===c)+") {\n              dotProd +=\n                getX(batch, xR, xC, "+l+") *\n                getW(wR, wC, "+l+", d2);\n            } else if ("+(2===c)+") {\n              vec2 xValues = vec2(\n                getX(batch, xR, xC, "+l+"),\n                getX(batch, xR, xC, "+l+" + 1)\n              );\n              vec2 wValues = vec2(\n                getW(wR, wC, "+l+", d2),\n                getW(wR, wC, "+l+" + 1, d2)\n              );\n              dotProd += dot(xValues, wValues);\n            } else if ("+(3===c)+") {\n              vec3 xValues = vec3(\n                getX(batch, xR, xC, "+l+"),\n                getX(batch, xR, xC, "+l+" + 1),\n                getX(batch, xR, xC, "+l+" + 2)\n              );\n              vec3 wValues = vec3(\n                getW(wR, wC, "+l+", d2),\n                getW(wR, wC, "+l+" + 1, d2),\n                getW(wR, wC, "+l+" + 2, d2)\n              );\n              dotProd += dot(xValues, wValues);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Xn=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,i=t.strideDepth,o=t.strideHeight,a=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,p=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n      const ivec3 strides = ivec3("+i+", "+o+", "+a+");\n      const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d2 = coords.u;\n\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xFCorner = xFRCCorner.x;\n        int xRCorner = xFRCCorner.y;\n        int xCCorner = xFRCCorner.z;\n\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\n        // values in that axis.\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+c+"; wF++) {\n          int xF = xFCorner + wF * "+s+";\n\n          if (xF < 0 || xF >= "+t.inDepth+") {\n            continue;\n          }\n\n          for (int wR = 0; wR < "+p+"; wR++) {\n            int xR = xRCorner + wR * "+u+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+h+"; wC++) {\n              int xC = xCCorner + wC * "+l+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n                vec4 xValues = vec4(\n                  getX(batch, xF, xR, xC, d1),\n                  getX(batch, xF, xR, xC, d1 + 1),\n                  getX(batch, xF, xR, xC, d1 + 2),\n                  getX(batch, xF, xR, xC, d1 + 3)\n                );\n                vec4 wValues = vec4(\n                  getW(wF, wR, wC, d1, d2),\n                  getW(wF, wR, wC, d1 + 1, d2),\n                  getW(wF, wR, wC, d1 + 2, d2),\n                  getW(wF, wR, wC, d1 + 3, d2)\n                );\n\n                dotProd += dot(xValues, wValues);\n              }\n\n              if ("+(1===d)+") {\n                dotProd +=\n                  getX(batch, xF, xR, xC, "+f+") *\n                  getW(wF, wR, wC, "+f+", d2);\n              } else if ("+(2===d)+") {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, "+f+"),\n                  getX(batch, xF, xR, xC, "+f+" + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, "+f+", d2),\n                  getW(wF, wR, wC, "+f+" + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if ("+(3===d)+") {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, "+f+"),\n                  getX(batch, xF, xR, xC, "+f+" + 1),\n                  getX(batch, xF, xR, xC, "+f+" + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, "+f+", d2),\n                  getW(wF, wR, wC, "+f+" + 1, d2),\n                  getW(wF, wR, wC, "+f+" + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Yn=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,p=t.outChannels/t.inChannels;this.userCode="\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+r+", "+i+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2 / "+p+";\n        int q = d2 - d1 * "+p+";\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n        for (int wR = 0; wR < "+l+"; wR++) {\n          int xR = xRCorner + wR * "+s+";\n\n          if (xR < 0 || xR >= "+e+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+c+"; wC++) {\n            int xC = xCCorner + wC * "+u+";\n\n            if (xC < 0 || xC >= "+n+") {\n              continue;\n            }\n\n            float xVal = getX(batch, xR, xC, d1);\n            float wVal = getW(wR, wC, d1, q);\n            dotProd += xVal * wVal;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Jn=function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,o=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=c,f="int xR; int xC; int xCOffset;",d=0;d<l;d++)for(var m=0;m<c;m++)f+="\n          vec4 xTexelR"+d+"C"+2*m+" = vec4(0.);\n          vec4 wR"+d+"C"+m+" = vec4(0.);\n          vec4 xR"+d+"C"+m+" = vec4(0.);";for(d=0;d<l;d++)for(var g=0;g<h;g++){if(f+="\n          xR = xRCorner + "+d*s+";\n          xC = xCCorner + "+(m=2*g)*u+";\n        ",1===a){if(m<c&&(f+=i%2==1?"\n                xCOffset = xC + 1;\n                if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+d+"C"+m+" = vec4(0.);\n                }\n\n                xCOffset = xC + 1 - 2;\n                if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n                  vec4 previous = getX(batch, xR, xCOffset, d1);\n                  xR"+d+"C"+m+" = vec4(previous.zw, xTexelR"+d+"C"+m+".xy);\n                } else {\n                  xR"+d+"C"+m+" = vec4(0, 0, xTexelR"+d+"C"+m+".xy);\n                }\n              ":"\n                if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n                  xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+d+"C"+m+" = vec4(0.);\n                }\n\n                xR"+d+"C"+m+" = xTexelR"+d+"C"+m+";\n              ",m+1<c)){var y=i%2==0?p(u):u;u%2==0&&i%2==1||u%2!=0&&i%2!=1?(f+="\n                  xCOffset = xC + "+i%2+" + "+y+";\n\n                  if(xR >= 0 && xR < "+e+" &&\n                    xCOffset >= 0 && xCOffset < "+n+") {\n                    xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n                ",u>1&&(f+="\n                    xCOffset -= 2;\n                    if(xR >= 0 && xR < "+e+" &&\n                      xCOffset >= 0 && xCOffset < "+n+") {\n                      xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n                    } else {\n                      xTexelR"+d+"C"+m+" = vec4(0.);\n                    }\n                  "),f+="\n                  xR"+d+"C"+(m+1)+" = vec4(\n                    xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".xy);\n                "):f+="\n                  xCOffset = xC + "+y+";\n\n                  if(xR >= 0 && xR < "+e+" &&\n                    xCOffset >= 0 && xCOffset < "+n+") {\n                    xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n\n                  xR"+d+"C"+(m+1)+" = xTexelR"+d+"C"+(m+2)+";\n                "}}else m<c&&(f+="\n              if(xR >= 0 && xR < "+e+") {\n            ",i%2==1?(f+="\n                xCOffset = xC + 1 - "+a+";\n                if(xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+d+"C"+m+" = vec4(0.);\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < "+n+") {\n                  xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xC + 1, d1);\n                } else {\n                  xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n                }\n\n                xR"+d+"C"+m+" = vec4(\n                  xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".zw);\n              ",m+1<c&&(f+="\n                  vec4 final = vec4(0.);\n                  xCOffset = xC + 1 + "+a+";\n                  if(xCOffset >= 0 && xCOffset < "+n+") {\n                    final = getX(batch, xR, xCOffset, d1);\n                  }\n                  xR"+d+"C"+(m+1)+" = vec4(xTexelR"+d+"C"+(m+2)+".xy, final.xy);\n                ")):(f+="\n                if(xC >= 0 && xC < "+n+") {\n                  xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+d+"C"+m+" = vec4(0.);\n                }\n\n                xCOffset = xC + "+a+";\n                if(xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n                }\n\n                xR"+d+"C"+m+" = vec4(\n                  xTexelR"+d+"C"+m+".xy, xTexelR"+d+"C"+(m+2)+".xy);\n              ",m+1<c&&(f+="\n                  xR"+d+"C"+(m+1)+" = vec4(\n                    xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".zw);\n                ")),f+="}");m<c&&(f+="\n            vec4 wTexelR"+d+"C"+m+" = getW("+d+", "+m+", d1, q);\n            wR"+d+"C"+m+" = vec4(wTexelR"+d+"C"+m+".xz, wTexelR"+d+"C"+m+".xz);\n          ",m+1<c&&(f+="\n              vec4 wTexelR"+d+"C"+(m+1)+" = getW("+d+", "+(m+1)+", d1, q);\n              wR"+d+"C"+(m+1)+" =\n                vec4(wTexelR"+d+"C"+(m+1)+".xz, wTexelR"+d+"C"+(m+1)+".xz);"))}for(d=0;d<l;d++)for(m=0;m<c;m++)f+="result += xR"+d+"C"+m+" * wR"+d+"C"+m+";";this.userCode="\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+r+", "+i+");\n\n      void main() {\n\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2;\n        int q = 0;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        vec4 result = vec4(0.);\n\n        "+f+"\n\n        setOutput(result);\n      }\n    "},Zn=function(t,e,n,r,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=t[0],a=t[1],s=t[2],u=t[3],l=e[0],c=n[0],p=n[1];this.outputShape=[l,c,p,u];var h="bilinear"===r?1:0,f=[a-1+".0",s-1+".0"],d=f[0],m=f[1],g=c>1?[""+(a-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],y=g[0],v=g[1],b=g[2],w=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],x=w[0],N=w[1],S=w[2];this.userCode="\n      const float height_ratio = float("+y+");\n      const float width_ratio = float("+x+");\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int y = coords[1];\n        int x = coords[2];\n        int d = coords[3];\n\n        // get box vals\n        float y1 = getBoxes(b,0);\n        float x1 = getBoxes(b,1);\n        float y2 = getBoxes(b,2);\n        float x2 = getBoxes(b,3);\n\n        // get image in batch index\n        int bInd = round(getBoxInd(b));\n        if(bInd < 0 || bInd >= "+o+") {\n          return;\n        }\n\n        float height_scale = "+v+";\n        float width_scale = "+N+";\n\n        float in_y = "+b+";\n        if( in_y < 0.0 || in_y > "+d+" ) {\n          setOutput(float("+i+"));\n          return;\n        }\n        float in_x = "+S+";\n        if( in_x < 0.0 || in_x > "+m+" ) {\n          setOutput(float("+i+"));\n          return;\n        }\n\n        vec2 sourceFracIndexRC = vec2(in_y,in_x);\n        if("+h+" == 1) {\n          // Compute the four integer indices.\n          ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n          ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n          float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n          float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n          float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n          float bottomRight = getImage(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n          vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n          float top = topLeft + (topRight - topLeft) * fracRC.y;\n          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n          float newValue = top + (bottom - top) * fracRC.x;\n          setOutput(newValue);\n        } else {\n          // Compute the coordinators of nearest neighbor point.\n          ivec2 sourceNearestRC = ivec2(floor(\n            sourceFracIndexRC + vec2(0.5,0.5)));\n          float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n          setOutput(newValue);\n        }\n      }\n    "},Qn=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,i=t[t.length-1],o=n?"<":">";this.userCode="\n      int getIndex(int i) {\n        "+(n?"return "+i+" -i - 1;":"return i;")+"\n      }\n\n      void main() {\n        "+Nn(r)+" coords = getOutputCoords();\n        int end = "+tr(r,"coords")+";\n        float val = 0.0;\n        for (int i = "+i+" - 1; i >= 0; i -= 1) {\n          int idx = getIndex(i);\n          if (idx "+o+" end) {\n            continue;\n          }\n          if (idx == end && "+e+") {\n            continue;\n          }\n          "+tr(r,"coords")+" = idx;\n          val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n        }\n        setOutput(val);\n      }\n    "};function tr(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var er=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n    void main() {\n      ivec4 coords = getOutputCoords();\n      int b = coords[0];\n      int h = "+this.getHeightCoordString()+";\n      int w = "+this.getWidthCoordString()+";\n      int d = "+this.getDepthCoordString()+";\n\n      int in_h = h / "+e+";\n      int offset_h = imod(h, "+e+");\n      int in_w = w / "+e+";\n      int offset_w = imod(w, "+e+");\n      int offset_d = (offset_h * "+e+" + offset_w) *\n        "+this.getOutputDepthSize()+";\n      int in_d = d + offset_d;\n\n      float result = "+this.getInputSamplingString()+";\n      setOutput(result);\n    }\n  "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),nr=function(t){this.variableNames=["A"];var e=cn();this.outputShape=t,this.userCode="\n      const float FLOAT_MAX = 1.70141184e38;\n      const float FLOAT_MIN = 1.17549435e-38;\n\n      lowp vec4 encode_float(highp float v) {\n        if (isNaN(v)) {\n          return vec4(255, 255, 255, 255);\n        }\n\n        highp float av = abs(v);\n\n        if(av < FLOAT_MIN) {\n          return vec4(0.0, 0.0, 0.0, 0.0);\n        } else if(v > FLOAT_MAX) {\n          return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n        } else if(v < -FLOAT_MAX) {\n          return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\n        }\n\n        highp vec4 c = vec4(0,0,0,0);\n\n        highp float e = floor(log2(av));\n        highp float m = exp2(fract(log2(av))) - 1.0;\n\n        c[2] = floor(128.0 * m);\n        m -= c[2] / 128.0;\n        c[1] = floor(32768.0 * m);\n        m -= c[1] / 32768.0;\n        c[0] = floor(8388608.0 * m);\n\n        highp float ebias = e + 127.0;\n        c[3] = floor(ebias / 2.0);\n        ebias -= c[3] * 2.0;\n        c[2] += floor(ebias) * 128.0;\n\n        c[3] += 128.0 * step(0.0, -v);\n\n        return c / 255.0;\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        "+e.output+" = encode_float(x);\n      }\n    "},rr="return real * expR - imag * expI;",ir="return real * expI + imag * expR;",or=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var i=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,o=n?r+".0":"1.0";this.userCode="\n      const float exponentMultiplier = "+i+";\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        "+t+"\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float("+r+");\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < "+r+"; i++) {\n          // x = (-2|2 * PI / N) * index * i;\n          float x = exponentMultiplierTimesIndexRatio * float(i);\n          float expR = cos(x);\n          float expI = sin(x);\n          float real = getReal(batch, i);\n          float imag = getImag(batch, i);\n\n          result +=\n              unaryOpComplex(real, expR, imag, expI) / "+o+";\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    "},ar=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n      uniform float value;\n      void main() {\n        // Input can be obtained from uniform value.\n        setOutput(value);\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),sr=function(t){this.variableNames=["A"];var e=cn(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n        vec4 values = "+e.texture2D+"(A, uv);\n        float value;\n        if (depth == 0) {\n          value = values.r;\n        } else if (depth == 1) {\n          value = values.g;\n        } else if (depth == 2) {\n          value = values.b;\n        } else if (depth == 3) {\n          value = values.a;\n        }\n\n        setOutput(floor(value * 255.0 + 0.5));\n      }\n    "},ur=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var i=Nn(this.rank),o=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],o=0;o<t.length;o++)o===e?i.push("int(getIndices("+r[o]+"))"):i.push(""+r[o]);return i.join()}(t,n);this.userCode="\n      void main() {\n        "+i+" resRC = getOutputCoords();\n        setOutput(getA("+o+"));\n      }\n    "};var lr,cr,pr=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=Nn(e.length),i=Nn(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n        "+r+" strides = "+r+"("+this.strides+");\n         void main() {\n          "+i+" coords = getOutputCoords();\n          int flattenIndex = 0;\n          for (int j = 0; j < "+this.sliceDim+"; j++) {\n            int index = round(getIndices(coords[0], j));\n            flattenIndex += index * "+o+";\n          }\n          setOutput(getX(flattenIndex, coords[1]));\n        }\n      "};function hr(t,e){return[e,t]}function fr(t,e){return t*e}function dr(t,e,n){var r=function(t,e){if(t%e!=0)throw new Error("unpackedSize ("+t+") must be a multiple of "+e);return t/e}(t.length,n);if(e.length<r)throw new Error("matrix length ("+e.length+") must be >= "+r);for(var i=0,o=0;o<t.length;o+=n)e[i++]=t[o]}function mr(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function gr(t,e){var n=mr(t,e);return n[0]*n[1]*4}function yr(t,e,n,r,i){var o=n*r;if(i.length<o)throw new Error("matrix length ("+i.length+") must be >= "+o);for(var a=r%2==1,s=n%2==1,u=Math.floor(r/2),l=Math.floor(n/2),c=Math.ceil(r/2),h=c*Math.ceil(n/2),f=p(n)*p(r),d=0;d<e;d++){for(var m=d*n*r,g=d*f,y=a?4:0,v=r+(a?1:0),b=g,w=m,x=m+r,N=0;N<l;++N){for(var S=0;S<u;++S)i[w++]=t[b++],i[w++]=t[b++],i[x++]=t[b++],i[x++]=t[b++];b+=y,w+=v,x+=v}if(a){b=g+4*(c-1);var C=m+r-1;for(y=4*c,v=2*r,N=0;N<l;++N)i[C]=t[b],i[C+r]=t[b+2],b+=y,C+=v}if(s){for(b=g+4*(h-c),C=m+(n-1)*r,S=0;S<u;++S)i[C++]=t[b++],i[C++]=t[b++],b+=2;a&&(i[m+n*r-1]=t[b])}}return i}function vr(t,e){var n=e();return xr(t),n}!function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(lr||(lr={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(cr||(cr={}));var br=!1;function wr(t){br=t}function xr(t){if(br){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+Er(t,e))}}var Nr=5.96e-8,Sr=65504;function Cr(t){return!!(Ut.get("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||Nr<Math.abs(t)&&Math.abs(t)<Sr)}function Er(t,e){switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+e}}function Ir(t,e){return $r(t,function(){return t.getExtension(e)},'Extension "'+e+'" not supported on this browser.')}function kr(t,e){var n=$r(t,function(){return t.createShader(t.VERTEX_SHADER)},"Unable to create vertex WebGLShader.");if(vr(t,function(){return t.shaderSource(n,e)}),vr(t,function(){return t.compileShader(n)}),!1===t.getShaderParameter(n,t.COMPILE_STATUS))throw console.log(t.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function Ar(t,e){var n=$r(t,function(){return t.createShader(t.FRAGMENT_SHADER)},"Unable to create fragment WebGLShader.");if(vr(t,function(){return t.shaderSource(n,e)}),vr(t,function(){return t.compileShader(n)}),!1===t.getShaderParameter(n,t.COMPILE_STATUS))throw function(t,e){var n=Tr.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],i=t.split("\n"),o=i.length.toString().length+2,a=i.map(function(t,e){return S((e+1).toString(),o)+t}),s=0,u=0;u<a.length;u++)s=Math.max(a[u].length,s);var l=a.slice(0,r-1),c=a.slice(r-1,r),p=a.slice(r);console.log(l.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+S(c[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join("\n"))}(e,t.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var Tr=/ERROR: [0-9]+:([0-9]+):/g;function Rr(t){return $r(t,function(){return t.createProgram()},"Unable to create WebGLProgram.")}function Dr(t,e){if(vr(t,function(){return t.linkProgram(e)}),!1===t.getProgramParameter(e,t.LINK_STATUS))throw console.log(t.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function Or(t,e){if(vr(t,function(){return t.validateProgram(e)}),!1===t.getProgramParameter(e,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function _r(t,e){var n=$r(t,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return vr(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,n)}),vr(t,function(){return t.bufferData(t.ARRAY_BUFFER,e,t.STATIC_DRAW)}),n}function Mr(t,e){var n=$r(t,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return vr(t,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,n)}),vr(t,function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,e,t.STATIC_DRAW)}),n}function Lr(){return 2===Ut.get("WEBGL_VERSION")?1:4}function Fr(t){return $r(t,function(){return t.createTexture()},"Unable to create WebGLTexture.")}function zr(t,e){var n=Ut.get("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function Pr(t){return $r(t,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Br(t,e,n,r,i,o,a){var s=t.getAttribLocation(e,n);return-1!==s&&(vr(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),vr(t,function(){return t.vertexAttribPointer(s,i,t.FLOAT,!1,o,a)}),vr(t,function(){return t.enableVertexAttribArray(s)}),!0)}function Ur(t,e,n){Xr(t,n),vr(t,function(){return t.activeTexture(t.TEXTURE0+n)}),vr(t,function(){return t.bindTexture(t.TEXTURE_2D,e)})}function Wr(t,e,n){return $r(t,function(){return t.getUniformLocation(e,n)},'uniform "'+n+'" not present in program.')}function Vr(t,e,n){return t.getUniformLocation(e,n)}function jr(t,e,n,r,i){vr(t,function(){return Ur(t,n,i)}),vr(t,function(){return t.uniform1i(r,i)})}function qr(t,e,n){vr(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),vr(t,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)})}function Gr(t,e){vr(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,e)}),vr(t,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function Hr(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Kr(t,e))}function Kr(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function $r(t,e,n){var r=vr(t,function(){return e()});if(null==r)throw new Error(n);return r}function Xr(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function Yr(t,e){return void 0===e&&(e=2),v(t.slice(0,t.length-e))}function Jr(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function Zr(t,e){var n;void 0===e&&(e=!1);var r=Ut.get("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?p(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var i=k(t);t=i.newShape}var o=v(t);if(t.length<=1&&o<=r)return[1,o];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var a=Yr(t),s=2,u=2;return t.length&&(s=(n=Jr(t))[0],u=n[1]),N(o=a*(s/2)*(u/2)).map(function(t){return 2*t})}return N(o)}function Qr(t){return t%2==0}function ti(t,e){if(b(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(Qr(n)&&Qr(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&Qr(t[0])&&Qr(e[0])}var ei=Object.freeze({callAndCheck:vr,enableDebugWebGLErrorChecking:wr,checkWebGLError:xr,canBeRepresented:Cr,getWebGLErrorMessage:Er,getExtensionOrThrow:Ir,createVertexShader:kr,createFragmentShader:Ar,createProgram:Rr,linkProgram:Dr,validateProgram:Or,createStaticVertexBuffer:_r,createStaticIndexBuffer:Mr,getNumChannels:Lr,createTexture:Fr,validateTextureSize:zr,createFramebuffer:Pr,bindVertexBufferToProgramAttribute:Br,bindTextureUnit:Ur,unbindTextureUnit:function(t,e){Xr(t,e),vr(t,function(){return t.activeTexture(t.TEXTURE0+e)}),vr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:Wr,getProgramUniformLocation:Vr,bindTextureToProgramUniformSampler:jr,bindCanvasToFramebuffer:function(t){vr(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),vr(t,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),vr(t,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:qr,unbindColorTextureFromFramebuffer:Gr,validateFramebuffer:Hr,getFramebufferErrorMessage:Kr,getBatchDim:Yr,getRowsCols:Jr,getTextureShapeFromLogicalShape:Zr,isReshapeFree:ti});function ni(t){var e=cn();return kr(t,e.version+"\n    precision highp float;\n    "+e.attribute+" vec3 clipSpacePos;\n    "+e.attribute+" vec2 uv;\n    "+e.varyingVs+" vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }")}function ri(t){return _r(t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ii(t){return Mr(t,new Uint16Array([0,1,2,2,1,3]))}function oi(t,e){var n,r,i,o,a,s,u,l,c=t;return 2===Ut.get("WEBGL_VERSION")?(n=c.R32F,r=c.R16F,i=c.RGBA16F,o=c.RGBA32F,a=c.RED,s=4,u=1,l=c.HALF_FLOAT):(n=t.RGBA,r=t.RGBA,i=t.RGBA,o=c.RGBA,a=t.RGBA,s=4,u=4,l=null!=e?e.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:o,textureFormatFloat:a,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:u,textureTypeHalfFloat:l}}function ai(t,e,n,r,i,o){zr(e,n);var a=Fr(t),s=t.TEXTURE_2D;return vr(t,function(){return t.bindTexture(s,a)}),vr(t,function(){return t.texParameteri(s,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),vr(t,function(){return t.texParameteri(s,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),vr(t,function(){return t.texParameteri(s,t.TEXTURE_MIN_FILTER,t.NEAREST)}),vr(t,function(){return t.texParameteri(s,t.TEXTURE_MAG_FILTER,t.NEAREST)}),vr(t,function(){return t.texImage2D(s,0,r,e,n,0,i,o,null)}),vr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)}),a}function si(t,e,n,r){var i=hr(e,n);return ai(t,i[0],i[1],r.internalFormatFloat,r.textureFormatFloat,t.FLOAT)}function ui(t,e,n,r){var i=hr(e,n);return ai(t,i[0],i[1],r.internalFormatHalfFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function li(t,e,n,r){var i=hr(e,n);return ai(t,i[0],i[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function ci(t,e,n,r){var i=mr(e,n);return ai(t,i[0],i[1],r.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function pi(t,e,n,r){var i=mr(e,n);return ai(t,i[0],i[1],r.internalFormatPackedHalfFloat,t.RGBA,r.textureTypeHalfFloat)}function hi(t,e,n){return vr(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,n)}),Br(t,e,"clipSpacePos",n,3,20,0)&&Br(t,e,"uv",n,2,20,12)}function fi(t,e,n){vr(t,function(){return t.bindTexture(t.TEXTURE_2D,e)}),vr(t,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n)}),vr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function di(t,e,n,r,i,o){zr(n,r),vr(t,function(){return t.bindTexture(t.TEXTURE_2D,e)}),vr(t,function(){return t.texSubImage2D(t.TEXTURE_2D,0,0,0,n,r,o,t.FLOAT,i)}),vr(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function mi(t,e,n,r,i,o,a){var s,u=hr(n,r),l=u[0],c=u[1],p=n*r;1===a.defaultNumChannels&&p===i.length?s=i:function(t,e,n){var r=fr(t.length,n);if(e.length<r)throw new Error("unpackedArray length ("+e.length+") must be >= "+r);for(var i=0,o=0;o<t.length;++o)e[i]=t[o],i+=n}(i,s=new Float32Array(p*o),o),di(t,e,l,c,s,a.textureFormatFloat)}function gi(t,e,n,r,i,o,a,s,u){var l=mr(o,a),c=l[0],h=l[1],f=new Float32Array(gr(o,a));(function(t,e,n,r,i){for(var o=r%2==1,a=n%2==1,s=Math.floor(r/2),u=Math.floor(n/2),l=Math.ceil(r/2),c=l*Math.ceil(n/2),h=p(n)*p(r),f=0;f<e;f++){for(var d=f*n*r,m=f*h,g=o?4:0,y=r,v=m,b=0;b<u;++b){for(var w=2*b*r,x=0;x<s;++x){var N=d+w+2*x;i[v]=t[N],i[v+1]=t[N+1],i[v+2]=t[N+y],i[v+3]=t[N+y+1],v+=4}v+=g}if(o){N=d+r-1,v=m+4*(l-1);var S=2*r;for(g=4*l,b=0;b<u;++b)i[v]=t[N],i[v+2]=t[N+r],N+=S,v+=g}if(a){for(N=d+(n-1)*r,v=m+4*(c-l),x=0;x<s;++x)i[v++]=t[N++],i[v++]=t[N++],v+=2;o&&a&&(i[m+h-4]=t[N])}}})(s,n,r,i,f),di(t,e,c,h,f,t.RGBA)}function yi(t,e,n,r,i){var o=e;if(2===Ut.get("WEBGL_VERSION")){var a=t,s=a.createBuffer();vr(t,function(){return t.bindBuffer(a.PIXEL_PACK_BUFFER,s)});var u=4*fr(n*r,i.downloadUnpackNumChannels);vr(t,function(){return t.bufferData(a.PIXEL_PACK_BUFFER,u,a.STREAM_READ)}),vr(t,function(){return a.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),vr(t,function(){return t.bindBuffer(a.PIXEL_PACK_BUFFER,null)}),o=s}return o}function vi(t,e,n,r,i){var o=t,a=new Float32Array(fr(n*r,i.downloadUnpackNumChannels));o.bindBuffer(o.PIXEL_PACK_BUFFER,e),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);var s=new Float32Array(n*r);return dr(a,s,i.downloadUnpackNumChannels),s}function bi(t,e,n,r){var i=hr(e,n),o=i[0],a=i[1],s=new Float32Array(fr(e*n,r.downloadUnpackNumChannels));vr(t,function(){return t.readPixels(0,0,o,a,r.downloadTextureFormat,t.FLOAT,s)});var u=new Float32Array(e*n);return dr(s,u,r.downloadUnpackNumChannels),u}function wi(t,e,n,r){var i=hr(e,n),o=i[0],a=i[1],s=new Uint8Array(fr(e*n,4));return vr(t,function(){return t.readPixels(0,0,o,a,r.downloadTextureFormat,t.UNSIGNED_BYTE,s)}),new Float32Array(s.buffer)}function xi(t,e,n,r,i,o,a,s){var u=t,l=new Float32Array(gr(o,a));u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null);var c=new Float32Array(v([n,r,i]));return yr(l,n,r,i,c),c}function Ni(t,e,n,r,i,o,a){var s=mr(i,o),u=s[0],l=s[1],c=new Float32Array(gr(i,o));vr(t,function(){return t.readPixels(0,0,u,l,t.RGBA,t.FLOAT,c)});var p=new Float32Array(v([e,n,r]));return yr(c,e,n,r,p)}var Si=Object.freeze({createVertexShader:ni,createVertexBuffer:ri,createIndexBuffer:ii,getTextureConfig:oi,createFloat32MatrixTexture:si,createFloat16MatrixTexture:ui,createUnsignedBytesMatrixTexture:li,createPackedMatrixTexture:ci,createFloat16PackedMatrixTexture:pi,bindVertexProgramAttributeStreams:hi,uploadPixelDataToTexture:fi,uploadMatrixToTexture:mi,uploadMatrixToPackedTexture:gi,maybeCreateBufferFromOutputTexture:yi,downloadFloat32MatrixFromBuffer:vi,downloadFloat32MatrixFromOutputTexture:bi,downloadByteEncodedFloatMatrixFromOutputTexture:wi,downloadPackedMatrixFromBuffer:xi,downloadMatrixFromPackedOutputTexture:Ni}),Ci=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.autoDebugValidate=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=Ut.get("WEBGL_VERSION");null!=t?(this.gl=t,function(t,e){a[t]=e}(e,t)):this.gl=u(e),1===Ut.get("WEBGL_VERSION")?(this.textureFloatExtension=Ir(this.gl,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),Ut.get("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=Ir(this.gl,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"))):this.colorBufferFloatExtension=Ir(this.gl,"EXT_color_buffer_float"),this.vertexBuffer=ri(this.gl),this.indexBuffer=ii(this.gl),this.framebuffer=Pr(this.gl),this.textureConfig=oi(this.gl,this.textureHalfFloatExtension)}return t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;vr(e,function(){return e.finish()}),vr(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),vr(e,function(){return e.deleteFramebuffer(t.framebuffer)}),vr(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),vr(e,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),vr(e,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},t.prototype.enableAutomaticDebugValidation=function(t){this.autoDebugValidate=t,wr(t)},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),si(this.gl,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),ui(this.gl,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),li(this.gl,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),fi(this.gl,t,e)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),pi(this.gl,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ci(this.gl,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(Gr(this.gl,this.framebuffer),this.outputTexture=null),vr(this.gl,function(){return e.gl.deleteTexture(t)})},t.prototype.uploadMatrixToTexture=function(t,e,n,r){this.throwIfDisposed();var i=Lr();return mi(this.gl,t,e,n,r,i,this.textureConfig)},t.prototype.uploadMatrixToPackedTexture=function(t,e,n,r,i,o,a){return this.throwIfDisposed(),gi(this.gl,t,e,n,r,i,o,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return bi(r.gl,e,n,r.textureConfig)})},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return wi(r.gl,e,n,r.textureConfig)})},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,i,o){return xi(this.gl,t,e,n,r,i,o,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e,n){return vi(this.gl,t,e,n,this.textureConfig)},t.prototype.maybeCreateBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=yi(this.gl,t,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(Ut.get("WEBGL_FENCE_API_ENABLED")){var i=t,o=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=i.clientWaitSync(o,0,0);return t===i.ALREADY_SIGNALED||t===i.CONDITION_SATISFIED},e=o}else Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return!0};return{query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n,r,i,o){var a=this;return this.downloadMatrixDriver(t,function(){return Ni(a.gl,e,n,r,i,o,a.textureConfig)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=Ar(e,t),r=ni(e),i=Rr(e);return vr(e,function(){return e.attachShader(i,r)}),vr(e,function(){return e.attachShader(i,n)}),Dr(e,i),this.autoDebugValidate&&Or(e,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=hi(e,this.program,this.vertexBuffer)),i},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&vr(this.gl,function(){return e.gl.deleteProgram(t)})},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.autoDebugValidate&&Or(this.gl,this.program),vr(this.gl,function(){return e.gl.useProgram(t)})},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?Wr(this.gl,t,e):Vr(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),vr(this.gl,function(){return n.gl.getAttribLocation(t,e)})},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),jr(this.gl,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=mr(e,n),i=r[0],o=r[1];this.setOutputMatrixTextureDriver(t,i,o)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&Or(this.gl,this.program),Hr(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.autoDebugValidate&&this.debugValidate(),vr(t,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),vr(this.gl,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Ir(this.gl,2===Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),i=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,i),i},t.prototype.endQuery=function(){if(2!==Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT)}},t.prototype.waitForQueryAndGetTime=function(t){return i(this,void 0,void 0,function(){var e=this;return o(this,function(n){switch(n.label){case 0:return[4,C(function(){return e.disposed||e.isQueryAvailable(t,Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e<t.length&&t[e]();++e);return e-1}(this.itemsToPoll.map(function(t){return t.isDoneFn})),e=0;e<=t;++e)(0,this.itemsToPoll[e].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(t+1)},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||C(function(){return n.pollItems(),0===n.itemsToPoll.length})},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),qr(this.gl,t,this.framebuffer),this.autoDebugValidate&&Hr(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(qr(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&Hr(this.gl)):Gr(this.gl,this.framebuffer)},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;qr(r,t,this.framebuffer),this.autoDebugValidate&&Hr(r),this.outputTexture=t,vr(r,function(){return r.viewport(0,0,e,n)}),vr(r,function(){return r.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var i=this;this.throwIfDisposed(),vr(this.gl,function(){return i.gl.scissor(t,e,n,r)})},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function Ei(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,i=e[n],o=i.shape;if(!b(r,o))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+o+" must match");if(!t.isUniform||!i.isUniform){var a=t.texShape,s=i.isUniform?null:i.texData.texShape;if(!b(a,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+s+" must match")}})}var Ii=function(t,e,n){this.variableNames=["A"],this.outputShape=t;var r=n.filterWidth,i=n.inChannels,o=n.strideWidth,a=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,p=s.left,h=s.top,f=i*r,d=cn();this.userCode="\n      void main() {\n        ivec2 rc = getOutputCoords();\n\n        vec4 result = vec4(0);\n\n        for(int row=0; row<=1; row++) {\n          for(int col=0; col<=1; col++) {\n            int blockIndex = rc.y + col;\n            int pos = rc.x + row;\n\n            if(blockIndex >= "+t[1]+" || pos >= "+t[0]+") continue;\n\n            int offsetY = int(blockIndex / ("+u+")) * "+a+" - "+h+";\n            int d0 = offsetY + "+c+" * (pos / "+f+");\n\n            if(d0 >= "+e[0]+" || d0 < 0) continue;\n\n            int offsetX = int(mod(float(blockIndex), "+u+".) * "+o+". - "+p+".);\n            int d1 = offsetX + "+l+" * (int(mod(float(pos), "+f+".) / "+i+".));\n\n            if(d1 >= "+e[1]+" || d1 < 0) continue;\n\n            result[row * 2 + col] = getA(d0, d1, int(mod(float(pos), "+i+".)));\n          }\n        }\n\n        "+d.output+" = result;\n      }\n    "},ki=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[];var o,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";o=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n        int d = coords[3];\n        float x = getX(b, r, c, d);\n        float sum = 0.0;\n        for (int j = -"+a+"; j <= "+a+"; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  "+s+") {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * "+o+";\n        setOutput(val);\n      }\n    "},Ai=function(t,e,n,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=i,this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n\n        float result = 0.0;\n        for (int d = 0; d < "+this.depth+"; ++d) {\n          int depthBegin = int(max(0.0, float(d - "+e+")));\n          int depthEnd = int(min(float("+this.depth+"),\n              float(d + "+e+" + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = "+this.depth+";\n\n          float norm = 0.0;\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd) {\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n            }\n            else {\n              break;\n            }\n          }\n\n          norm = float("+r+") * norm + float("+n+");\n\n          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd){\n              float dyi = -2.0 * float("+r+")\n                * float("+i+")\n                * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * "+i+");\n              }\n              if (k == coords[3]) {\n                dyi *= getDy(b, r, c, d);\n                result += dyi;\n              }\n            }\n            else {\n              break;\n            }\n          }\n      }\n      setOutput(result);\n      }\n    "},Ti=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,i=t.effectiveFilterHeight,o=t.effectiveFilterWidth,a=i-1-t.padInfo.top,s=o-1-t.padInfo.left,u=i*o-1;this.userCode="\n      const ivec2 pads = ivec2("+a+", "+s+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+i+";\n          wR += "+r+") {\n          float dyR = float(dyRCorner + wR) / "+e+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+o+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+n+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n            int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n            // Get the current value, check it against the value from the\n            // position matrix.\n            int curPosValue = wR * "+o+" + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Ri=function(t,e,n,r,i,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i=!1),void 0===o&&(o=null),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var a=n?t[1]:t[2],s=Math.ceil(a/2),u=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",c=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],p=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],h="",f="";o&&(h="vec4 activation(vec4 x) {\n        "+o+"\n      }",f="result = activation(result);");var d=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),this.userCode="\n      "+h+"\n\n      const float sharedDimension = "+s+".0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        for (int i = 0; i < "+s+"; i++) {\n          vec4 a = getMatrixA(rc.x, "+u+");\n          vec4 b = getMatrixB(rc.x, "+l+");\n\n          result += ("+c[0]+" * "+p[0]+") + ("+c[1]+" * "+p[1]+");\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        "+d+"\n\n        "+f+"\n\n        setOutput(result);\n      }\n    "},Di=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n      uniform float seed;\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n\n        float r = random(seed);\n        float cdf = 0.0;\n\n        for (int i = 0; i < "+(e-1)+"; i++) {\n          cdf += getProbs(batch, i);\n\n          if (r < cdf) {\n            setOutput(float(i));\n            return;\n          }\n        }\n\n        // If no other event happened, last event happened.\n        setOutput(float("+(e-1)+"));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),Oi=function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int index = round(getIndices(coords.x));\n        setOutput(mix(float("+r+"), float("+n+"),\n                      float(index == coords.y)));\n      }\n    "},_i=function(t){this.variableNames=["A"],this.isPackShader=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{var n=an("rc",e),r=Nn(e),i=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",i=t-2;i<t;i++)r+=n[i]+" >= "+e[i],i<t-1&&(r+="||");return r}(e,t,n),o=function(t,e,n,r){if(1===t)return"";var i=r.slice(-2);return"\n    int r = "+i[0]+";\n    int c = "+i[1]+";\n    int rp1 = r + 1;\n    int cp1 = c + 1;\n\n    bool cEdge = cp1 >= "+e+";\n    bool rEdge = rp1 >= "+n+";\n  "}(e,t[t.length-1],t[t.length-2],n),a=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var o=(0===r?"r":"rp1")+", "+(0===i?"c":"cp1"),a=2;a<t;a++)o=e[e.length-1-a]+","+o;n.push(o)}return n}(n,e);return 1===n?"getA(rc),\n            rc + 1 >= "+t[0]+" ? 0. : getA(rc + 1),\n            0, 0":"getA("+r[0]+"),\n          cEdge ? 0. : getA("+r[1]+"),\n          rEdge ? 0. : getA("+r[2]+"),\n          rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n        void main() {\n          "+r+" rc = getOutputCoords();\n\n          if("+i+") {\n            setOutput(vec4(0));\n          } else {\n            "+o+"\n\n            setOutput(vec4("+a+"));\n          }\n        }\n      "}};var Mi=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,i=Nn(r),o=e.map(function(t){return t[0]}).join(","),a=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n      "+i+" start = "+i+"("+o+");\n      "+i+" end = "+i+"("+a+");\n\n      void main() {\n        "+i+" outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(float("+n+"));\n        } else {\n          "+i+" coords = outC - start;\n          setOutput(getX("+s+"));\n        }\n      }\n    ":"\n        int start = "+o+";\n        int end = "+a+";\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(float("+n+"));\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      "},Li=function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,i=Nn(r),o=e.map(function(t){return t[0]}).join(","),a=e.map(function(e,n){return e[0]+t[n]}).join(","),s=an("rc",r),u=an("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[i+" rc = outputLoc;",s[r-1]+" += 1;\n       if("+l+") {\n      ",1===r?"":"}\n       rc = outputLoc;\n       "+s[r-2]+" += 1;\n       if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":"  "+s[r-1]+" += 1;\n         if("+l+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,m=1===r?2:4;d<m;d++)f+="\n        "+p[d]+"\n        if ("+h+") {\n          result["+d+"] = float("+n+");\n        } else {\n          "+i+" source = rc - start;\n          result["+d+"] = getChannel(getX("+u.join()+"), "+c+");\n        }\n      ";f+=1===r?"} ":"}}",this.userCode="\n      const "+i+" start = "+i+"("+o+");\n      const "+i+" end = "+i+"("+a+");\n\n      void main() {\n        "+i+" outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        "+f+"\n        setOutput(result);\n      }\n    "},Fi=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,i=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=t.padInfo.top,p=t.padInfo.left;this.outputShape=t.outShape;var h="avg"===e,f="0.0";if(h||(f="-1.0 / 1e-20"),n)this.userCode="\n        const ivec2 strides = ivec2("+i+", "+o+");\n        const ivec2 pads = ivec2("+c+", "+p+");\n\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int batch = coords[0];\n          int d = coords[3];\n\n          ivec2 xRCCorner = coords.yz * strides - pads;\n          int xRCorner = xRCCorner.x;\n          int xCCorner = xRCCorner.y;\n\n          // max/min x(?, ?, d) to get y(yR, yC, d).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n          float avgValue = 0.0;\n\n          for (int wR = 0; wR < "+u+";\n              wR += "+a+") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+l+";\n                wC += "+s+") {\n              int xC = xCCorner + wC;\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float value = getX(batch, xR, xC, d);\n\n              // If a min / max value has already been found, use it. If not,\n              // use the current value.\n              float currMinMaxValue = mix(\n                  value, minMaxValue, minMaxValueFound);\n              if (value >= currMinMaxValue) {\n                minMaxValue = value;\n                minMaxValueFound = 1.0;\n                minMaxPosition = wR * "+l+" + wC;\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ";else{var d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var m=4*Math.floor(r/4),g=r%4,y="\n      if ("+h+") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    ";this.userCode="\n      const ivec2 strides = ivec2("+i+", "+o+");\n      const ivec2 pads = ivec2("+c+", "+p+");\n      const float initializationValue = "+f+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xR, int xC, int d) {\n        if (xC < 0 || xC >= "+t.inWidth+") {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xR, xC, d);\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // max/min x(?, ?, d) to get y(yR, yC, d).\n        // ? = to be determined\n        vec4 minMaxValue = vec4("+f+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < "+u+";\n            wR += "+a+") {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= "+t.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+m+"; wC += 4) {\n            int xC = xCCorner + wC * "+s+";\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              getValue(batch, xR, xC + 3 * "+s+", d)\n            );\n\n            "+y+"\n          }\n\n          int xC = xCCorner + "+m+";\n          if ("+(1===g)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            "+y+"\n          } else if ("+(2===g)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              initializationValue,\n              initializationValue\n            );\n\n            "+y+"\n          } else if ("+(3===g)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              initializationValue\n            );\n\n            "+y+"\n          }\n        }\n        setOutput("+d+");\n      }\n    "}},zi=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,i=t.inSize,o=Math.ceil(i/n);this.outputShape=[r,o];var a="0.0",s="";"prod"===e?a="1.0":"min"===e?(a="1.0 / 1e-20",s="min"):"max"===e&&(a="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,p="\n      if ("+("sum"===e)+") {\n        sumValue += dot(values, ones);\n      } else if ("+("prod"===e)+") {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = "+s+"(values, minMaxValue);\n      }\n    ",h="vec4";"all"===e?(a="1.0",p="\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      ",h="bvec4"):"any"===e&&(a="0.0",p="\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      ",h="bvec4");var f="";i%n>0&&(f="\n        if (inIdx < 0 || inIdx >= "+i+") {\n          return initializationValue;\n        }\n      "),this.userCode="\n      const float initializationValue = "+a+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        "+f+"\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+n+";\n\n        vec4 minMaxValue = vec4("+a+");\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < "+l+"; i += 4) {\n          int inIdx = inOffset + i;\n          "+h+" values = "+h+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          "+p+"\n        }\n\n        int inIdx = inOffset + "+l+";\n        if ("+(1===c)+") {\n          "+h+" values = "+h+"(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          "+p+"\n        } else if ("+(2===c)+") {\n          "+h+" values = "+h+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          "+p+"\n        } else if ("+(3===c)+") {\n          "+h+" values = "+h+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          "+p+"\n        }\n        setOutput("+u+");\n      }\n    "},Pi=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),n+="\n        "+i+"\n        "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n          int flatIndex = getFlatIndex(thisRC);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result["+r+"] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        "+(r>0?"}":"")+"\n      "}this.userCode="\n      "+function(t){return"\n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      "+pn(["r","c","d"],t)+"\n      return ivec3(r, c, d);\n    }\n  "}(e)+"\n      "+function(t){return"\n    int getFlatIndex(ivec3 coords) {\n      return round("+function(t,e){if(t.length!==e.length)throw new Error("Vectors to be dotted must be of the same length -got "+t.length+" and "+e.length);for(var n=[],r=Math.floor(t.length/4),i=t.length%4,o=0;o<r;o++){var a=t.slice(4*o,4*o+4),s=e.slice(4*o,4*o+4);n.push(hn(a)+", "+hn(s))}return 0!==i&&(a=t.slice(4*r),s=e.slice(4*r),1===a.length&&(a=a.map(function(t){return"float("+t+")"}),s=s.map(function(t){return"float("+t+")"})),n.push(hn(a)+", "+hn(s))),n.map(function(t,e){return"dot("+t+")"}).join("+")}(["coords.x","coords.y","coords.z"],V(t).map(function(t){return t.toString()}).concat(["1."]))+");\n    }\n  "}(t)+"\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = "+t[1]+";\n        int cols = "+t[2]+";\n\n        "+n+"\n\n        setOutput(result);\n      }\n    "};var Bi=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],o=r[2],a=t.shape,s=a[1],u=a[2],l=[n&&s>1?i-1:i,n&&u>1?o-1:o],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+p+");\n        const float widthScale = float("+h+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+d+");\n\n        const int winHeight = int("+m+");\n        const int winWidth = int("+g+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(startRLerp - float(winHeight / 2));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(startCLerp - float(winWidth / 2));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), "+(i-1)+".0));\n            float dxRLerp = dxR - float(topDxRIndex);\n            float inverseDxRLerp = 1.0 - dxRLerp;\n\n            float dxC = float(dyC) * widthScale;\n            int leftDxCIndex = int(floor(dxC));\n            int rightDxCIndex = int(min(ceil(dxC), "+(o-1)+".0));\n            float dxCLerp = dxC - float(leftDxCIndex);\n            float inverseDxCLerp = 1.0 - dxCLerp;\n\n            if (r == topDxRIndex && c == leftDxCIndex) {\n              // topLeft\n              accumulator +=\n                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n            }\n\n            if (r == topDxRIndex && c == rightDxCIndex) {\n              // topRight\n              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == leftDxCIndex) {\n              // bottomLeft\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == rightDxCIndex) {\n              // bottomRight\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    "},Ui=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+");\n      const vec2 inputShapeRC = vec2("+o+".0, "+a+".0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the four integer indices.\n        ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n        ivec2 sourceCeilRC = ivec2(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n        float top = topLeft + (topRight - topLeft) * fracRC.y;\n        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n        float newValue = top + (bottom - top) * fracRC.x;\n\n        setOutput(newValue);\n      }\n    "},Wi=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+",\n          "+u[1]/l[1]+");\n      const vec3 inputShapeRC = vec3("+o+".0, "+a+".0,\n                                     "+a+".0);\n\n      float getAValue(int b, int r, int c, int d) {\n        return getChannel(getA(b, r, c, d), vec2(c, d));\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        // Calculate values for next column in yRC.z.\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n        // Fractional source index.\n        vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the four integer indices.\n        ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n        ivec3 sourceCeilRC = ivec3(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n        \n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < "+(s-1)+"; \n        bool hasNextRow = coords.z < "+(n-1)+";\n\n        // In parallel, construct four corners for all four components in\n        // packed 2x2 cell.\n        vec4 topLeft = vec4(\n          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 bottomLeft = vec4(\n          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 topRight = vec4(\n          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec4 bottomRight = vec4(\n          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n        vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n        vec4 newValue = mix(top, bottom, fracRC.x);\n\n        setOutput(newValue);\n      }\n    "},Vi=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],o=r[2],a=t.shape,s=a[1],u=a[2],l=[n&&s>1?i-1:i,n&&u>1?o-1:o],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+p+");\n        const float widthScale = float("+h+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+d+");\n\n        const int winHeight = int("+m+");\n        const int winWidth = int("+g+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float sourceFracRow =\n              float("+l[0]+") *\n                (float(dyR) / float("+c[0]+"));\n\n            float sourceFracCol =\n                float("+l[1]+") *\n                  (float(dyC) / float("+c[1]+"));\n\n            int sourceNearestRow = int(min(\n                float(int("+i+") - 1),\n                "+n+" ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int("+o+") - 1),\n                "+n+" ? float(round(sourceFracCol)) :\n                                  float(floor(sourceFracCol))));\n\n            if (r == sourceNearestRow && c == sourceNearestCol) {\n              accumulator += getDy(b, dyR, dyC, d);\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    "},ji=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],o=t[1],a=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?o-1:o,r&&n>1?a-1:a],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+");\n      const vec2 inputShapeRC = vec2("+o+".0, "+a+".0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec2 sourceNearestRC = ivec2(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    "},qi=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),i=Nn(n);this.userCode="\n      void main() {\n        "+i+" coords = getOutputCoords();\n        setOutput(getX("+r+"));\n      }\n    "}else this.userCode="\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX("+t[0]+" - coord - 1));\n        }\n      "},Gi=function(t,e,n,r,i,o,a){void 0===a&&(a=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var s=Nn(i.length),u=Nn(o.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",f=e>1?"strides[j]":"strides";this.userCode="\n        "+s+" strides = "+s+"("+i+");\n\n        void main() {\n          "+u+" coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < "+t+"; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < "+e+"; j++) {\n              int index = round("+c+");\n              flattenedIndex += index * "+f+";\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += "+h+";\n              found = true;\n            }\n          }\n          setOutput(mix(getDefaultValue(), sum, float(found)));\n        }\n      "},Hi=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,i=t.inSize,o=t.numSegments,a=o*Math.ceil(i/n);this.outputShape=[r,a];var s=4*Math.floor(n/4),u=n%4,l="\n        sumValue += dot(values, segFilter);\n    ",c="";i%n>0&&(c="\n        if (inIdx < 0 || inIdx >= "+i+") {\n          return initializationValue;\n        }\n      ");var p="";i%n>0&&(p="\n        if (inIdx < 0 || inIdx >= "+i+") {\n          return -1.0;\n        }\n      "),this.userCode="\n      const float initializationValue = 0.0;\n\n      float getValue(int batch, int inIdx) {\n        "+c+"\n        return getX(batch, inIdx);\n      }\n\n      float getSegmentIdAtIndex(int inIdx) {\n        "+p+"\n        return getSegmentIds(inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = int(floor(float(outIdx) / float(\n          "+o+")) * float("+n+"));\n        int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < "+s+"; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n          );\n\n          "+l+"\n        }\n\n        int inIdx = inOffset + "+s+";\n        if ("+(1===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            0,\n            0,\n            0\n          );\n\n          "+l+"\n        } else if ("+(2===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n              0,\n              0\n          );\n\n          "+l+"\n        } else if ("+(3===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            0\n          );\n\n          "+l+"\n        }\n        setOutput(sumValue);\n      }\n    "},Ki=function(t,e,n){var r,i;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)i="resRC",r="resRC";else{for(var o=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],s=[],u=0;u<e.length;u++)s.push(""+o[u]),u<t&&a.push(""+o[u]);r=a.join(),i=s.join()}var l=Nn(n);this.userCode="\n      void main() {\n        "+l+" resRC = getOutputCoords();\n        float cVal = getC("+r+");\n        if (cVal >= 1.0) {\n          setOutput(getA("+i+"));\n        } else {\n          setOutput(getB("+i+"));\n        }\n      }\n    "},$i=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Nn(this.rank),r="uniform int start["+this.rank+"];",i=function(t){if(1===t)return"sourceLoc";if(t<=6)return Xi.slice(0,t).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n        "+n+" sourceLoc;\n        "+n+" coords = getOutputCoords();\n        "+t.map(function(t,e){return"sourceLoc."+Xi[e]+" = start["+e+"] + coords."+Xi[e]+";"}).join("\n")+"\n      ",this.userCode="\n      "+r+"\n      void main() {\n        "+e+"\n        setOutput(getSource("+i+"));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Xi=["x","y","z","w","u","v"];var Yi=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Nn(this.rank),n=an("coords",this.rank),r=an("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",o="getChannel(getSource("+r.join()+"), "+i+")",a="\n      result.x = "+o+";\n      if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n        ++"+r[this.rank-1]+";\n        result.y = "+o+";\n        --"+r[this.rank-1]+";\n      }\n    ",s=1===this.rank?"":"\n      --"+n[this.rank-1]+";\n      if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n        ++"+r[this.rank-2]+";\n        result.z = "+o+";\n        if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n          ++"+r[this.rank-1]+";\n          result.w = "+o+";\n        }\n      }\n    ",u=this.rank<=4?"sourceLoc = coords +\n            "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n      uniform int start["+this.rank+"];\n      void main() {\n        "+e+" coords = getOutputCoords();\n        "+e+" sourceLoc;\n        "+u+" \n        vec4 result = vec4(0.);\n        "+a+"\n        "+s+"\n        setOutput(result);\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),Ji=function(t,e,n,r){this.variableNames=["x"];var i=n.filter(function(t,e){return-1===r.indexOf(e)});this.outputShape=i;var o=n.length,a=Nn(n.length),s=Nn(i.length),u="";if(1===o)u="coords * strides + begin";else{var l=0;u=n.map(function(t,e){return-1===r.indexOf(e)?(l++,1===i.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(l-1)+"] * strides["+e+"] + begin["+e+"]"):"begin["+e+"]"}).join(",")}this.userCode="\n      "+a+" begin = "+a+"("+t+");\n      "+a+" strides = "+a+"("+e+");\n\n      void main() {\n        "+s+" coords = getOutputCoords();\n        setOutput(getX("+u+"));\n      }\n    "},Zi=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,i=Qi(e,n),o=to(t,i,n);if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),this.freeTextures[o].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var a=this.freeTextures[o].shift();return this.usedTextures[o].push(a),a}return this.numUsedTextures++,this.log(),i===cr.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===cr.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===cr.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===cr.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===cr.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[o].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var i=to(e,Qi(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(t),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[i],a=o.indexOf(t);if(a<0)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(a,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function Qi(t,e){if(t===lr.UPLOAD)return e?cr.PACKED_2X2_FLOAT32:cr.UNPACKED_FLOAT32;if(t===lr.RENDER||null==t)return e?Ut.get("WEBGL_RENDER_FLOAT32_ENABLED")?cr.PACKED_2X2_FLOAT32:cr.PACKED_2X2_FLOAT16:Ut.get("WEBGL_RENDER_FLOAT32_ENABLED")?cr.UNPACKED_FLOAT32:cr.UNPACKED_FLOAT16;if(t===lr.DOWNLOAD||t===lr.PIXELS)return cr.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function to(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var eo=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var i=Nn(this.rank),o=function(t){var e=t.length;if(e>5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],i=0;i<t.length;i++)r.push("imod("+n[i]+", "+t[i]+")");return r.join()}(t);this.userCode="\n      void main() {\n        "+i+" resRC = getOutputCoords();\n        setOutput(getA("+o+"));\n      }\n    "};var no=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var i=Nn(this.rank),o=function(t){var e=t.length;if(e>6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),i=0;i<t.length;i++)r[t[i]]=n[i];return r.join()}(e);this.userCode="\n    void main() {\n      "+i+" resRC = getOutputCoords();\n      setOutput(getA("+o+"));\n    }\n    "};var ro=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var i=Nn(this.rank),o=on("rc",this.rank),a=new Array(this.rank);for(r=0;r<e.length;r++)a[e[r]]=o[r];var s="vec2("+a.slice(-2).join()+")",u="++"+o[this.rank-1]+" < "+n[this.rank-1],l="getChannel(getA("+a.join()+"), "+s+")";this.userCode="\n    void main() {\n      "+i+" rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = "+l+";\n      if("+u+") {\n        result[1] = "+l+";\n      }\n      --"+o[this.rank-1]+";\n      if(++"+o[this.rank-2]+" < "+n[this.rank-2]+") {\n        result[2] = "+l+";\n        if("+u+") {\n          result[3] = "+l+";\n        }\n      }  \n      setOutput(result);\n    }\n    "},io=1.7580993408473768,oo=1.0507009873554805,ao=function(){function t(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode="\n      uniform float NAN;\n      float unaryOperation(float x) {\n        "+e+"\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    "}return t.prototype.getCustomSetupFunc=function(){var t=this;return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"NAN"),null==t.startLoc)||e.gl.uniform1f(t.startLoc,NaN)}},t}(),so="if (isNaN(x)) return x;",uo="return x;",lo=so+"\n  return (x < 0.0) ? 0.0 : x;\n",co="\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = "+io+";\n  float scale = "+oo+";\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var po="return exp(x);",ho=so+"\n  return sin(x);\n",fo=so+"\n  return cos(x);\n",mo=so+"\n  return atan(x);\n",go=so+"\n  if (x < 1.0) return NAN;\n  return log(x + sqrt(x * x - 1.0));",yo=so+"\n  if ((x < -1.0) || (x > 1.0)) return NAN;\n  return (log(1.0 + x) - log(1.0 - x)) / 2.0;",vo="return x;",bo="\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n\n  result.r = isNaN(x.r) ? x.r : result.r;\n  result.g = isNaN(x.g) ? x.g : result.g;\n  result.b = isNaN(x.b) ? x.b : result.b;\n  result.a = isNaN(x.a) ? x.a : result.a;\n\n  return result;\n",wo=function(){function t(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n      uniform float NAN;\n      vec4 unaryOperation(vec4 x) {\n        "+e+"\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    "}return t.prototype.getCustomSetupFunc=function(){var t=this;return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"NAN"),null==t.startLoc)||e.gl.uniform1f(t.startLoc,NaN)}},t}(),xo=function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=an("rc",e),r=Nn(e),i=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(e,n),o=n.slice(-2),a=e<=1?"rc":"vec2("+o.join(",")+")";this.userCode="\n      void main() {\n        "+r+" rc = getOutputCoords();\n        vec4 packedInput = getA("+i+");\n\n        setOutput(getChannel(packedInput, "+a+"));\n      }\n    "};var No=Ce({concat_:function(t,e){void 0===e&&(e=0),d(t.length>=1,function(){return"Pass at least one tensor to concat"});var n=Se(t,"tensors","concat");e=I(e,n[0].shape)[0];var r=le(n.map(function(t){return t.shape}),e);if(0===v(r))return Re([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var i=n.map(function(t){return t.shape});!function(t,e){var n=t[0].length;t.forEach(function(t,e){d(t.length===n,function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")"})}),d(e>=0&&e<n,function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."});var r=t[0];t.forEach(function(t,i){for(var o=0;o<n;o++)d(o===e||t[o]===r[o],function(){return"Error in concat"+n+"D: Shape of tensors["+i+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+i+"."})})}(i,e);var o=n;return Ut.engine.runKernel(function(t){return t.concat(n,e)},o,function(t){var n=i.map(function(t){return t[e]});return ko(t,n,e).map(function(t){return function(){return t}})})}}),So=Ce({concat1d_:function(t){return No(t,0)}}),Co=Ce({concat2d_:function(t,e){return No(t,e)}}),Eo=Ce({concat3d_:function(t,e){return No(t,e)}}),Io=Ce({concat4d_:function(t,e){return No(t,e)}}),ko=Ce({split_:function(t,e,n){void 0===n&&(n=0);var r,i=Ne(t,"x","split");return n=I(n,i.shape)[0],"number"==typeof e?(d(i.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(i.shape[n]/e)):(d(i.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),r=e),Ut.engine.runKernel(function(t){return t.split(i,r,n)},{$x:i},function(t){return{$x:function(){return No(t,n)}}})}});function Ao(t,e){return t(e={exports:{}},e.exports),e.exports}var To=Ao(function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),Ro=Ao(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),Do=Ao(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Oo=Ao(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),_o=Ao(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,o=e.i;return e.w=r=r+1640531527|0,n=i[o+34&127],t=i[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[o]=n^t,e.i=o,n+(r^r>>>16)|0},function(t,e){var n,r,i,o,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,o=-32;o<u;++o)e&&(r^=e.charCodeAt((o+32)%e.length)),0===o&&(a=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,i=0==(n=s[127&o]^=r+a)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=a,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),Mo=Ao(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),Lo=Ao(function(t){!function(e,n){var r,i=this,o=256,a=6,s="random",u=n.pow(o,a),l=n.pow(2,52),c=2*l,p=o-1;function h(t,h,g){var y=[],v=d(function t(e,n){var r,i=[],o=typeof e;if(n&&"object"==o)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=i.navigator,a=n&&n.plugins;return[+new Date,i,a,i.screen,m(e)]}}():t,3),y),b=new function(t){var e,n=t.length,r=this,i=0,a=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i<o;)s[i]=i++;for(i=0;i<o;i++)s[i]=s[a=p&a+t[i%n]+(e=s[i])],s[a]=e;(r.g=function(t){for(var e,n=0,i=r.i,a=r.j,s=r.S;t--;)e=s[i=p&i+1],n=n*o+s[p&(s[i]=s[a=p&a+e])+(s[a]=e)];return r.i=i,r.j=a,n})(o)}(y),w=function(){for(var t=b.g(a),e=u,n=0;t<l;)t=(t+n)*o,e*=o,n=b.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,d(m(b.S),e),(h.pass||g||function(t,e,r,i){return i&&(i.S&&f(i,b),t.state=function(){return f(b,{})}),r?(n[s]=t,e):t})(w,v,"global"in h?h.global:this==n,h.state)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function d(t,e){for(var n,r=t+"",i=0;i<r.length;)e[p&i]=p&(n^=19*e[p&i])+r.charCodeAt(i++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=h,d(n.random(),e),t.exports){t.exports=h;try{r=require("crypto")}catch(t){}}}([],Math)});Lo.alea=To,Lo.xor128=Ro,Lo.xorwow=Do,Lo.xorshift7=Oo,Lo.xor4096=_o,Lo.tychei=Mo;var Fo=Lo.alea,zo=function(){function t(t,e,n,r,i){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var o=i||Math.random();this.random=Fo(o.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var i=void 0,o=void 0,a=void 0;do{a=(i=2*this.random()-1)*i+(o=2*this.random()-1)*o}while(a>=1||0===a);var s=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*o*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}();function Po(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",$(t),new ot(t,e,n)}function Bo(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var Uo=Ce({batchToSpaceND_:function(t,e,n){var r=Ne(t,"x","batchToSpaceND"),i=e.reduce(function(t,e){return t*e});return d(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),d(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length  "+e.length}),d(r.shape[0]%i==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+i}),Ut.engine.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Wo=Ce({cast_:function(t,e){var n=Ne(t,"x","cast");return Ut.engine.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Vo=Ce({clone_:function(t){var e=Ne(t,"x","clone",null);return Ut.engine.runKernel(function(t){return lt.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),jo=Ce({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var i=Ne(t,"x","cumsum"),o=ae([e|=0],i.rank),a=i;null!=o&&(a=i.transpose(o));var s=ue(1,i.rank)[0],u=Ut.engine.runKernel(function(t){return t.cumsum(a,s,n,r)},{permutedX:a},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=o&&(u=u.transpose(o)),u}}),qo=Ce({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=Ne(t,"x","depthToSpace"),i="NHWC"===n?r.shape[1]:r.shape[2],o="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];return d(i*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n      "+i+" and "+e+"  for depthToSpace with input shape\n      "+r.shape}),d(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n      "+o+" and "+e+" for depthToSpace with input shape\n          "+r.shape}),d(a%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+a+" for depthToSpace with input shape "+r.shape}),Ut.engine.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),Go=Ce({expandDims_:function(t,e){void 0===e&&(e=0);var n=Ne(t,"x","expandDims");d(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(d(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),ra(n,r)}}),Ho=Ce({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var i=Po([t,e],r),o=t<=e?t:e,a=0;a<o;++a)i.set(1,a,a);var s=i.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return sa(Go(s,0),[n[0],1,1]);if(2===n.length)return sa(Go(Go(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return sa(Go(Go(Go(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.")}}),Ko=Ce({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var i=Ne(t,"logits","multinomial"),o=i.size,a=i.rank;if(o<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+o+".");if(a>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);n=n||Math.random();var s=1===a?i.as2D(1,-1):i,u=Ut.engine.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===a?u.as1D():u}}),$o=Ce({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var i=Ne(t,"indices","oneHot","int32"),o=i.shape.concat([e]);return i=i.flatten(),Ut.engine.runKernel(function(t){return t.oneHot(i,e,n,r)},{$indices:i},function(t){return{$indices:function(){return Be(i.shape,"float32")}}}).reshape(o)}}),Xo=Ce({pad_:function(t,e,n){void 0===n&&(n=0);var r=Ne(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var i=e.map(function(t){return t[0]});return Ut.engine.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(i,r.shape)}}})}}),Yo=Ce({pad1d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),Xo(t,[e],n)}}),Jo=Ce({pad2d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),Xo(t,e,n)}}),Zo=Ce({pad3d_:function(t,e,n){return void 0===n&&(n=0),d(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),Xo(t,e,n)}}),Qo=Ce({pad4d_:function(t,e,n){return void 0===n&&(n=0),d(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),Xo(t,e,n)}}),ta=Ce({rand_:function(t,e,n){var r=v(t),i=null;if(null==n||"float32"===n)i=new Float32Array(r);else if("int32"===n)i=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);i=new Uint8Array(r)}for(var o=0;o<r;o++)i[o]=e();return lt.make(t,{values:i},n)}}),ea=Ce({randomNormal_:function(t,e,n,r,i){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var o=new zo(e,n,r,!1,i),a=Po(t,r),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),na=Ce({randomUniform_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var i=Po(t,r),o=0;o<i.values.length;o++)i.values[o]=f(e,n);return i.toTensor()}}),ra=Ce({reshape_:function(t,e){var n=Ne(t,"x","reshape",null);return e=E(e,n.size),d(n.size===v(e),function(){return"new shape and old shape must have the same number of elements."}),Ut.engine.runKernel(function(t){return t.reshape(n,e)},{$x:n},function(t){return{$x:function(){return t.reshape(n.shape)}}})}}),ia=Ce({spaceToBatchND_:function(t,e,n){var r=Ne(t,"x","spaceToBatchND");return d(r.rank>=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),d(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),d(r.shape.reduce(function(t,r,i){return i>0&&i<=e.length?t&&(r+n[i-1][0]+n[i-1][1])%e[i-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),Ut.engine.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),oa=Ce({squeeze_:function(t,e){var n=Ne(t,"x","squeeze");return ra(n,k(n.shape,e).newShape)}}),aa=Ce({stack_:function(t,e){void 0===e&&(e=0);var n=Se(t,"tensors","stack");if(d(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,i=n[0].shape,o=n[0].dtype;d(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){m(i,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){d(o===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var a=n.map(function(t){return t.expandDims(e)});return No(a,e)}}),sa=Ce({tile_:function(t,e){var n=Ne(t,"x","tile");return d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),Ut.engine.runKernel(function(t){return t.tile(n,e)},{$x:n},function(t){return{$x:function(){var r=qe(n);if(1===n.rank)for(var i=0;i<e[0];++i)r=r.add(t.slice([i*n.shape[0]],[n.shape[0]]));else if(2===n.rank)for(i=0;i<e[0];++i)for(var o=0;o<e[1];++o)r=r.add(t.slice([i*n.shape[0],o*n.shape[1]],[n.shape[0],n.shape[1]]));else if(3===n.rank)for(i=0;i<e[0];++i)for(o=0;o<e[1];++o)for(var a=0;a<e[2];++a)r=r.add(t.slice([i*n.shape[0],o*n.shape[1],a*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else{if(4!==n.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+n.rank+" tensors yet.");for(i=0;i<e[0];++i)for(o=0;o<e[1];++o)for(a=0;a<e[2];++a)for(var s=0;s<e[3];++s)r=r.add(t.slice([i*n.shape[0],o*n.shape[1],a*n.shape[2],s*n.shape[3]],[n.shape[0],n.shape[1],n.shape[2],n.shape[3]]))}return r}}})}}),ua=Ce({truncatedNormal_:function(t,e,n,r,i){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var o=new zo(e,n,r,!0,i),a=Po(t,r),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),la=Ce({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=Ne(t,"x","unstack");return d(e>=-n.shape.length&&e<n.shape.length,function(){return"Axis = "+e+" is not in [-"+n.shape.length+", "+n.shape.length+")"}),e<0&&(e+=n.shape.length),Ut.engine.runKernel(function(t){return t.unstack(n,e)},{$x:n},function(t){return{$x:function(){return aa(t,e)}}})}}),ca=function(t,e){return i(this,void 0,void 0,function(){var n,r,i,a,s,u,l,c,p,h;return o(this,function(o){switch(o.label){case 0:return n=Ne(t,"x","setdiff1d"),r=Ne(e,"y","setdiff1d"),d(n.dtype===r.dtype,function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."}),d(1===n.rank,function(){return"x should be 1D tensor, but got x ("+n.shape+")."}),d(1===r.rank,function(){return"y should be 1D tensor, but got y ("+r.shape+")."}),[4,n.data()];case 1:return i=o.sent(),[4,r.data()];case 2:for(a=o.sent(),s=new Set(a),u=0,p=0;p<i.length;p++)s.has(i[p])||u++;for(l=new ot([u],n.dtype),c=new ot([u],"int32"),p=0,h=0;p<i.length;p++)s.has(i[p])||(l.values[h]=i[p],c.values[h]=p,h++);return[2,[l.toTensor(),c.toTensor()]]}})})};function pa(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var i=Po(t,"int32"),o=Po([n.length,t.length],"int32");for(r=0;r<n.length;r++){var a=i.indexToLoc(n[r]),s=r*t.length;o.values.set(a,s)}return o.toTensor()}var ha=function(){function t(t){if(this.gpgpu=t,this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.lruDataGPU=[],this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.binaryCache={},this.disposed=!1,Ut.get("WEBGL_VERSION")<1)throw new Error("WebGL is not supported on this device");if(null==t){var e=u(Ut.get("WEBGL_VERSION"));this.gpgpu=new Ci(e),this.canvas=e.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpuCreatedLocally=!1,this.canvas=t.gl.canvas;this.textureManager=new Zi(this.gpgpu)}return t.prototype.register=function(t,e,n){if(this.texData.has(t))throw new Error("Data buffer is already registered");this.texData.set(t,{shape:e,dtype:n})},t.prototype.setDataMover=function(t){this.texData=new Ge(t)},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=[t.height,t.width],r=[t.height,t.width,e];if(Ut.get("IS_BROWSER")){if(!(t instanceof HTMLVideoElement||t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof ImageData))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+t.constructor.name);if(t instanceof HTMLVideoElement){if(null==this.fromPixels2DContext){if("complete"!==document.readyState)throw new Error("The DOM is not ready yet. Please call tf.browser.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object");this.fromPixels2DContext=document.createElement("canvas").getContext("2d")}this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),t=this.fromPixels2DContext.canvas}}var i=this.makeTensorHandle(n,"int32");this.texData.get(i.dataId).usage=lr.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(i.dataId),t);var o=new sr(r),a=this.compileAndRun(o,[i]);return this.disposeData(i.dataId),a},t.prototype.makeTensorHandle=function(t,e){var n={};return this.register(n,t,e),{dataId:n,shape:t,dtype:e}},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendWebGL.write(): values can not be null");if(Ut.get("DEBUG"))for(var n=0;n<e.length;n++){var r=e[n];if(!Cr(r))throw Error("The value "+r+" cannot be represented on this device.")}var i=this.texData.get(t),o=i.texture,a=i.texShape,s=i.usage,u=i.dtype,l=i.isPacked;if("complex64"===u)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");null!=o&&(this.releaseTexture(t,o,a,s,u,l),i.texture=null,i.texShape=null),i.usage=lr.UPLOAD,i.values=e},t.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,i=e.complexTensors,o=e.slice,a=e.shape;if(null!=o){var s=new ao(a,"return x;"),u=this.compileAndRun(s,[{dataId:t,shape:a,dtype:r}]),l=this.readSync(u.dataId);return u.dispose(),l}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var c,p,h=null!=this.activeTimers;return h&&(c=performance.now()),p="complex64"===r?Xe(i.real.dataSync(),i.imag.dataSync()):this.getValuesFromTexture(t),h&&(this.downloadWaitMs+=performance.now()-c),this.convertAndCacheOnCPU(t,p)},t.prototype.read=function(t){return i(this,void 0,void 0,function(){var e,n,r,i,a,s,u,l,c,p,h,f,d,m,g,y,b,w,x,N,S,C,E,I;return o(this,function(o){switch(o.label){case 0:if(this.pendingRead.has(t))return r=this.pendingRead.get(t),[2,new Promise(function(t){return r.push(t)})];if(i=this.texData.get(t),a=i.texture,s=i.values,u=i.texShape,l=i.isPacked,c=i.shape,p=i.slice,h=i.dtype,null!=p)return f=new ao(c,"return x;"),d=this.compileAndRun(f,[{dataId:t,shape:c,dtype:h}]),m=this.read(d.dataId),d.dispose(),[2,m];if(null!=s)return[2,this.convertAndCacheOnCPU(t)];if(this.pendingRead.set(t,[]),!Ut.get("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Ut.get("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return g=u[1],y=u[0],l&&(e=mr(u[0],u[1]),g=e[0],y=e[1]),b=this.gpgpu.maybeCreateBufferFromTexture(a,y,g),[4,this.gpgpu.createAndWaitForFence()];case 1:return o.sent(),b instanceof WebGLTexture?w=this.getValuesFromTexture(t):(x=v(c),l?(N=Yr(c),S=1,C=1,c.length&&(n=Jr(c),S=n[0],C=n[1]),w=this.gpgpu.downloadPackedMatrixFromBuffer(b,N,S,C,u[0],u[1]).subarray(0,x)):w=this.gpgpu.downloadFloat32MatrixFromBuffer(b,u[0],u[1]).subarray(0,x)),E=this.convertAndCacheOnCPU(t,w),I=this.pendingRead.get(t),this.pendingRead.delete(t),I.forEach(function(t){return t(E)}),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)),[2,E]}})})},t.prototype.getValuesFromTexture=function(t){var e,n=this,r=this.texData.get(t),i=r.shape,o=r.dtype,a=r.texture,s=r.texShape,u=v(i);if(Ut.get("WEBGL_DOWNLOAD_FLOAT_ENABLED")){if(this.texData.get(t).isPacked){var l=Yr(i),c=1,p=1;return i.length&&(c=(e=Jr(i))[0],p=e[1]),this.gpgpu.downloadMatrixFromPackedTexture(a,l,c,p,s[0],s[1]).subarray(0,u)}return this.gpgpu.downloadFloat32MatrixFromOutputTexture(a,s[0],s[1]).subarray(0,u)}var h=this.makeTensorHandle(i,"float32");h.size=v(i),this.texData.get(h.dataId).usage=lr.DOWNLOAD;var f=Gt(function(){var e=new nr(i);return n.compileAndRun(e,[{shape:i,dtype:o,dataId:t}],h,null,!1)}),d=this.texData.get(f.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(d.texture,d.texShape[0],d.texShape[1]).subarray(0,u);return this.disposeData(h.dataId),m},t.prototype.time=function(t){return i(this,void 0,void 0,function(){var e,n,r,i,a,s,u;return o(this,function(o){switch(o.label){case 0:return e=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,t(),i=y(this.activeTimers.map(function(t){return t.query})).filter(function(t){return null!=t}),a=y(this.activeTimers.map(function(t){return t.name})).filter(function(t){return null!=t}),this.activeTimers=e,r&&(this.programTimersStack=null),[4,Promise.all(i)];case 1:return s=o.sent(),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:h(s),getExtraProfileInfo:function(){return s.map(function(t,e){return{name:a[e],ms:t}}).map(function(t){return t.name+": "+t.ms}).join(", ")},wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}})})},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},t.prototype.startTimer=function(){return Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null}},t.prototype.endTimer=function(t){return Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=performance.now(),t)},t.prototype.getQueryTime=function(t){return i(this,void 0,void 0,function(){var e;return o(this,function(n){return Ut.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]})})},t.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){var e=this.texData.get(t),n=e.texture,r=e.dtype,i=e.texShape,o=e.usage,a=e.complexTensors,s=e.isPacked,u=e.slice;if(null!=n){var l=u&&u.origDataId||t,c=this.dataRefCount.get(l);c>1?this.dataRefCount.set(l,c-1):(this.dataRefCount.delete(l),this.releaseTexture(t,n,i,o,r,s),this.texData.delete(t))}null!=a&&(a.real.dispose(),a.imag.dispose())}},t.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},t.prototype.getCPUBackend=function(){return Ut.get("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Ut.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.size<e})},t.prototype.getGPGPUContext=function(){return this.gpgpu},t.prototype.getCanvas=function(){return this.canvas},t.prototype.complex=function(t,e){var n=this.makeOutputArray(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:Ut.engine.keep(t.clone()),imag:Ut.engine.keep(e.clone())},n},t.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone()},t.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone()},t.prototype.slice=function(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);var r=this.texData.get(t.dataId).isPacked,i=ve(t.shape,e,n);if(r||!i){var o=Ut.get("WEBGL_PACK_ARRAY_OPERATIONS")?new Yi(n):new $i(n),a=o.getCustomSetupFunc(e);return this.compileAndRun(o,[t],null,a)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},t.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),i=lt.make(n,{},t.dtype,this),o=this.texData.get(i.dataId);Object.assign(o,r),o.shape=n,o.dtype=t.dtype;var a=be(e,t.strides);r.slice&&(a+=r.slice.flatOffset),o.slice={flatOffset:a,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(o.slice.origDataId)||1;return this.dataRefCount.set(o.slice.origDataId,s+1),i},t.prototype.stridedSlice=function(t,e,n,r,i,o,a,s,u){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r,i,o,a,s,u);var l=me(t.shape,e,n,r,i,o,a,s,u),c=l[0],p=l[1],h=l[2],f=p.filter(function(t,e){return-1===h.indexOf(e)});if(f.some(function(t){return 0===t}))return Re([],f);var d=new Ji(c,r,p,h);return this.compileAndRun(d,[t])},t.prototype.reverse=function(t,e){var n=new qi(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.concat=function(t,e){if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>Ut.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(t.length/2),r=this.concat(t.slice(0,n),e),i=this.concat(t.slice(n),e);return this.concat([r,i],e)}if(Ut.get("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var o=new Wn(t.map(function(t){return t.shape}),e);return this.compileAndRun(o,t)}var a=le(t.map(function(t){return t.shape}),e),s=t.map(function(t){return t.as2D(-1,v(t.shape.slice(e)))}),u=new Un(s.map(function(t){return t.shape}));return this.compileAndRun(u,s).reshape(a)},t.prototype.neg=function(t){var e=new ao(t.shape,"return -x;");return this.compileAndRun(e,[t])},t.prototype.batchMatMul=function(t,e,n,r){var i=n?t.shape[2]:t.shape[1],o=r?e.shape[1]:e.shape[2],a=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===i||1===o)&&a>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===o?t:t.as3D(s,a,1),l=1===o?2:1,c=1===o?e.as3D(s,1,a):e;return this.multiply(u,c).sum(l,!0)}var p=vt(t.dtype,e.dtype),h=new Ri(t.shape,[s,i,o],n,r),f=this.makePackedTensor(h.outputShape,p);return this.compileAndRun(h,[t,e],f)},t.prototype.fusedBatchMatMul=function(t,e,n,r,i,o){var a=n?t.shape[2]:t.shape[1],s=r?e.shape[1]:e.shape[2],u=t.shape[0],l=vt(t.dtype,e.dtype),c=new Ri(t.shape,[u,a,s],n,r,!!i,o?function(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?vo:uo;if("relu"===t)return e?bo:lo;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}(o,!0):null),p=this.makePackedTensor(c.outputShape,l),h=[t,e];return i&&h.push(i),this.compileAndRun(c,h,p)},t.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),i=new Dn(Tn,t.shape,e.shape),o=new Dn(Rn,t.shape,e.shape),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],s=this.compileAndRun(i,a),u=this.compileAndRun(o,a),l=this.complex(s,u);return s.dispose(),u.dispose(),l}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Mn,t.dtype);var c=new Ln(Mn,t.shape,e.shape),p=this.makeOutputArray(c.outputShape,t.dtype);return this.compileAndRun(c,[t,e],p)},t.prototype.batchNormalization=function(t,e,n,r,i,o){var a=[t,e,n],s=null;null!=o&&(s=o.shape,a.push(o));var u=null;if(null!=i&&(u=i.shape,a.push(i)),Ut.get("WEBGL_PACK_BATCHNORMALIZATION")){var l=new An(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(l,a)}var c=new kn(t.shape,e.shape,n.shape,s,u,r);return this.compileAndRun(c,a)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){var o=new ki(t.shape,e,n,r,i);return this.compileAndRun(o,[t])},t.prototype.LRNGrad=function(t,e,n,r,i,o,a){var s=new Ai(e.shape,r,i,o,a);return this.compileAndRun(s,[e,n,t])},t.prototype.tile=function(t,e){var n=new eo(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.pad=function(t,e,n){var r=Ut.get("WEBGL_PACK_ARRAY_OPERATIONS")?new Li(t.shape,e,n):new Mi(t.shape,e,n);return this.compileAndRun(r,[t])},t.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=Ut.get("WEBGL_PACK_ARRAY_OPERATIONS")?new ro(t.shape,e):new no(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new ur(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},t.prototype.batchToSpaceND=function(t,e,n){d(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=Jt(t.shape,e,r),o=Zt(i.length,e.length),a=Qt(t.shape,e,r),s=te(n,e.length),u=ee(a,n,e.length);return t.reshape(i).transpose(o).reshape(a).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){d(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=[[0,0]];i.push.apply(i,n);for(var o=1+e.length;o<t.shape.length;++o)i.push([0,0]);var a=t.pad(i),s=Jt(a.shape,e,r,!1),u=Zt(s.length,e.length,!1),l=Qt(a.shape,e,r,!1);return a.reshape(s).transpose(u).reshape(l)},t.prototype.reduce=function(t,e,n){var r=t.shape[0],i=t.shape[1],o=he(i),a=new zi({windowSize:o,inSize:i,batchSize:r},e),s=a.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],n);return this.compileAndRun(a,[t],c),1===c.shape[1]?c:this.reduce(c,e,n)},t.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],i=t.shape[1];null!=n&&(r=n.shape[0],i=n.shape[1]);var o=he(i),a=new rn({windowSize:o,inSize:i,batchSize:r},e,null==n),s=a.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],"int32"),p=[t];return null!=n&&p.push(n),this.compileAndRun(a,p,c),1===c.shape[1]?c:this.argReduce(t,e,c)},t.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,i=he(r[r.length-1]),o=new En(r,i,e,null==n),a=this.makePackedTensor(o.outputShape,"int32"),s=null==n?[t]:[t,n];return this.compileAndRun(o,s,a),a.rank===t.rank?this.argReducePacked(t,e,a):a},t.prototype.sum=function(t,e){oe("sum",e,t.rank);var n=re(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i),a=bt(t.dtype);return this.reduce(o,"sum",a).reshape(r)},t.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=re(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i),a=bt(t.dtype);return this.reduce(o,"prod",a).reshape(r)},t.prototype.unsortedSegmentSum=function(t,e,n){var r=0,i=ae([r],t.rank),o=t;null!=i&&(o=t.transpose(i),r=ue(1,t.rank)[0]);var a=function(t,e,n){for(var r=[],i=t.length,o=0;o<i;o++)o!==e?r.push(t[o]):r.push(n);return r}(o.shape,r,n),s=v([o.shape[r]]),u=o.as2D(-1,s),l=bt(t.dtype),c=this.segOpCompute(u,"unsortedSegmentSum",e,l,n).reshape(a);return null!=i&&(c=c.transpose(se(i))),c},t.prototype.segOpCompute=function(t,e,n,r,i){var o=t.shape[0],a=t.shape[1],s=function(t,e){var n,r=!1;for(t<=pe?(n=t,r=!0):n=W(t,Math.floor(Math.sqrt(t)));!r;){if(n>e||n===t){r=!0;break}n=W(t,n+1)}return n}(a,i),u=new Hi({windowSize:s,inSize:a,batchSize:o,numSegments:i},e),l=u.outputShape,c=l[0],p=l[1],h=this.makeOutputArray([c,p],r);return this.compileAndRun(u,[t,n],h),h.shape[1]===i?h:(n=Ve(0,i).tile([a/s]),this.segOpCompute(h,e,n,r,i))},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(oe("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!Ut.get("WEBGL_PACK_REDUCE")||t.rank<=2){var i=re(t.shape,r),o=i[0],a=v(i[1]),s=t.as2D(-1,a);return this.argReduce(s,n).reshape(o)}return this.argReducePacked(t,n)},t.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},t.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},t.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var i=new Qn(t.shape,n,r);return this.compileAndRun(i,[t])},t.prototype.equal=function(t,e){if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(equal(a, b));\n","bool");var n=new Ln("return float(a == b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.notEqual=function(t,e){if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(notEqual(a, b));\n","bool");var n=new Ln("return float(a != b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThan(a, b));\n","bool");var n=new Ln("return float(a < b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.lessEqual=function(t,e){if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThanEqual(a, b));\n","bool");var n=new Ln("return float(a <= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThan(a, b));\n","bool");var n=new Ln("return float(a > b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greaterEqual=function(t,e){if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThanEqual(a, b));\n","bool");var n=new Ln("return float(a >= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalNot=function(t){var e=new ao(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new Ln("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalOr=function(t,e){if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n","bool");var n=new Ln("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.select=function(t,e,n){var r=new Ki(t.rank,e.shape,e.rank),i=this.makeOutputArray(r.outputShape,vt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],i)},t.prototype.where=function(t){Yt("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return pa(t.shape,e)},t.prototype.topk=function(t,e,n){return nn(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){oe("min",e,t.rank);var n=re(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"min",o.dtype).reshape(r)},t.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS")?new Fn("\n  vec4 result = vec4(min(a, b));\n  vec4 isNaN = min(vec4(isNaN(a)) + vec4(isNaN(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Ln("\n  if (isNaN(a)) return a;\n  if (isNaN(b)) return b;\n\n  return min(a, b);\n",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.mod=function(t,e){var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS")?new Fn("\n  vec4 result = mod(a, b);\n  vec4 isNaN = vec4(equal(b, vec4(0.0)));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Ln("if (b == 0.0) return NAN;\n  return mod(a, b);",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);oe("max",e,t.rank);var n=re(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"max",o.dtype).reshape(r)},t.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS")?new Fn("\n  vec4 result = vec4(max(a, b));\n  vec4 isNaN = min(vec4(isNaN(a)) + vec4(isNaN(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Ln("\n  if (isNaN(a)) return a;\n  if (isNaN(b)) return b;\n\n  return max(a, b);\n",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.all=function(t,e){oe("all",e,t.rank);var n=re(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(r)},t.prototype.any=function(t,e){oe("any",e,t.rank);var n=re(t.shape,e),r=n[0],i=v(n[1]),o=t.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS")?new Fn("return (a - b) * (a - b);",t.shape,e.shape):new Ln("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){var n=new Ln("if (a == b) return 1.0;\n  return a / b;",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t,e],r)},t.prototype.floorDiv=function(t,e){if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  vec4 resultSign = sign(a) * sign(b);\n  ivec4 ia = round(a);\n  ivec4 ib = round(b);\n  ivec4 result = ia / ib;\n  ivec4 amodb = ia - ib * result;\n\n  // Vectorize INT_DIV\n  // if (resultSign < 0.0 && amodb != 0) result -= 1;\n  // return float(result);\n  return vec4(result -\n     ivec4(lessThan(resultSign, vec4(0.0))) * ivec4(notEqual(amodb, ivec4(0))));\n","int32");var n=new Ln("\n  float resultSign = sign(a) * sign(b);\n  int ia = round(a);\n  int ib = round(b);\n  int result = ia / ib;\n  int amodb = ia - ib * result;\n\n  if (resultSign < 0.0 && amodb != 0) {\n    result -= 1;\n  }\n  return float(result);\n",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[t,e],r)},t.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,On);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=vt(t.dtype,e.dtype);if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,On,n);var r=new Ln(On,t.shape,e.shape),i=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],i)},t.prototype.packedBinaryOp=function(t,e,n,r){var i=new Fn(n,t.shape,e.shape),o=this.makePackedTensor(i.outputShape,r);return this.compileAndRun(i,[t,e],o)},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,i=this.texData.get(t.dataId),o=this.texData.get(e.dataId),a=[[i.complexTensors.real,o.complexTensors.real],[i.complexTensors.imag,o.complexTensors.imag]].map(function(i){var o=i[0],a=i[1],s=r.makeComplexComponentTensorHandle(t,o),u=r.makeComplexComponentTensorHandle(e,a),l=new Ln(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,vt(o.dtype,a.dtype));return r.compileAndRun(l,[s,u],c)}),s=a[0],u=a[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},t.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},t.prototype.addN=function(t){for(var e=t[0],n=1;n<t.length;n++)e=this.add(e,t[n]);return e},t.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,_n);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=vt(t.dtype,e.dtype);if(Ut.get("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,_n,t.dtype);var r=new Ln(_n,t.shape,e.shape),i=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],i)},t.prototype.pow=function(t,e){var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS"),r=n?new Fn("\n  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n  vec4 result = multiplier * pow(abs(a), b);\n\n  vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Ln("\nif(a < 0.0 && floor(b) < b){\n  return NAN;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n    pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),i=vt(t.dtype,e.dtype),o=n?this.makePackedTensor(r.outputShape,i):this.makeOutputArray(r.outputShape,i),a=r.getCustomSetupFunc();return this.compileAndRun(r,[t,e],o,a)},t.prototype.ceil=function(t){var e=new ao(t.shape,"return ceil(x);");return this.compileAndRun(e,[t])},t.prototype.floor=function(t){var e=new ao(t.shape,"return floor(x);");return this.compileAndRun(e,[t])},t.prototype.sign=function(t){var e=new ao(t.shape,"\n  if (isNaN(x)) { return 0.0; }\n  return sign(x);\n");return this.compileAndRun(e,[t])},t.prototype.round=function(t){var e=new ao(t.shape,"\n  // OpenGL ES does not support round function.\n  // The algorithm is based on banker's rounding.\n  float base = floor(x);\n  if ((x - base) < 0.5) {\n    return floor(x);\n  } else if ((x - base) > 0.5) {\n    return ceil(x);\n  } else {\n    if (mod(base, 2.0) == 0.0) {\n      return base;\n    } else {\n      return base + 1.0;\n    }\n  }\n");return this.compileAndRun(e,[t])},t.prototype.exp=function(t){var e;return e=Ut.get("WEBGL_PACK")?new wo(t.shape,po):new ao(t.shape,po),this.compileAndRun(e,[t])},t.prototype.expm1=function(t){var e=new ao(t.shape,"return exp(x) - 1.0;");return this.compileAndRun(e,[t])},t.prototype.log=function(t){var e,n=(e=Ut.get("WEBGL_PACK")?new wo(t.shape,"\n  vec4 result = log(x);\n  vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n  result.r = isNaN.r == 1.0 ? NAN : result.r;\n  result.g = isNaN.g == 1.0 ? NAN : result.g;\n  result.b = isNaN.b == 1.0 ? NAN : result.b;\n  result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n  return result;\n"):new ao(t.shape,"if (x < 0.0) return NAN;\n  return log(x);")).getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.log1p=function(t){var e=new ao(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new ao(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},t.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new ao(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new ao(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new ao(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e;return e=Ut.get("WEBGL_PACK")?new wo(t.shape,bo):new ao(t.shape,lo),this.compileAndRun(e,[t])},t.prototype.prelu=function(t,e){var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS")?new Fn("\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",t.shape,e.shape):new Ln("return (a < 0.) ? b * a : a;",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.elu=function(t){var e=new ao(t.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS")?new Fn("\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new Ln("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.selu=function(t){var e=new ao(t.shape,co);return this.compileAndRun(e,[t])},t.prototype.int=function(t){var e=new ao(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},t.prototype.clip=function(t,e,n){var r,i=(r=Ut.get("WEBGL_PACK_CLIP")?new Pn(t.shape):new zn(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,i)},t.prototype.abs=function(t){var e=new ao(t.shape,"return abs(x);");return this.compileAndRun(e,[t])},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Bn(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},t.prototype.sigmoid=function(t){var e=new ao(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new ao(t.shape,"\n  float epsilon = 1.1920928955078125e-7;\n  float threshold = log(epsilon) + 2.0;\n\n  bool too_large = x > -threshold;\n  bool too_small = x < threshold;\n\n  float result;\n  float exp_x = exp(x);\n\n  if (too_large){\n    result = x;\n  }\n  else if (too_small){\n    result = exp_x;\n  }\n  else{\n    result = log(exp_x + 1.0);\n  }\n  return result;\n");return this.compileAndRun(e,[t])},t.prototype.sin=function(t){var e=new ao(t.shape,ho);return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new ao(t.shape,fo);return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new ao(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new ao(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new ao(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new ao(t.shape,mo);return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=Ut.get("WEBGL_PACK_BINARY_OPERATIONS")?new Fn("\n  vec4 result = atan(a, b);\n  vec4 isNaN = min(vec4(isNaN(a)) + vec4(isNaN(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Ln("\n  if (isNaN(a)) return a;\n  if (isNaN(b)) return b;\n\n  return atan(a, b);\n",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.sinh=function(t){var e=new ao(t.shape,"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.cosh=function(t){var e=new ao(t.shape,"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.tanh=function(t){var e=new ao(t.shape,"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},t.prototype.asinh=function(t){var e=new ao(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new ao(t.shape,go),n=e.getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.atanh=function(t){var e=new ao(t.shape,yo),n=e.getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.erf=function(t){var e=new ao(t.shape,'\n  // Error function is calculated approximately with elementary function.\n  // See "Handbook of Mathematical Functions with Formulas,\n  // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n  float p = 0.3275911;\n  float a1 = 0.254829592;\n  float a2 = -0.284496736;\n  float a3 = 1.421413741;\n  float a4 = -1.453152027;\n  float a5 = 1.061405429;\n\n  float t = 1.0 / (1.0 + p * x);\n  return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},t.prototype.step=function(t,e){var n=new ao(t.shape,function(t){return void 0===t&&(t=0),so+"\n    return x > 0.0 ? 1.0 : float("+t+");\n  "}(e));return this.compileAndRun(n,[t])},t.prototype.conv2dByMatMul=function(t,e,n){var r=t.shape,i=this.texData.get(t.dataId),o=n.inChannels,a=r[0]*r[1]*r[2],s=n.outChannels,u=(1===a||1===s)&&o>1e3,l=r[2]%2!=0&&!!i.isPacked;if(u||!Ut.get("WEBGL_LAZILY_UNPACK")||!Ut.get("WEBGL_PACK_BINARY_OPERATIONS")||!l){var c=this.reshape(t,[1,r[0]*r[1]*r[2],n.inChannels]),p=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.batchMatMul(c,p,!1,!1),n.outShape)}var h=lt.make([1,r[0]*r[1]*(r[2]+1),n.inChannels],{dataId:t.dataId},t.dtype,this),f=i.shape;i.shape=i.shape.slice(),i.shape[i.shape.length-2]++,d(ti(i.shape,h.shape),function(){return"packed reshape "+i.shape+" to "+h.shape+" isn't free"});var m=this.reshape(e,[1,n.inChannels,n.outChannels]),g=this.batchMatMul(h,m,!1,!1),y=this.texData.get(g.dataId);return d(y.isPacked,function(){return"batchMatMul result is expected to be packed"}),i.shape=f,y.shape=n.outShape,lt.make(n.outShape,{dataId:g.dataId},g.dtype,this)},t.prototype.conv2dWithIm2Row=function(t,e,n){var r=n.filterWidth,i=n.filterHeight,o=n.inChannels,a=n.outWidth,s=n.outHeight,u=r*i*o,l=s*a,c=[u,l],p=t.squeeze([0]),h=e.reshape([1,u,-1]),f=new Ii(c,p.shape,n),d=this.compileAndRun(f,[p]).reshape([1,c[0],c[1]]),m=new Ri(d.shape,[1,l,n.outChannels],!0,!1);return this.compileAndRun(m,[d,h]).reshape([1,s,a,n.outChannels])},t.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(Ut.get("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new $n(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new jn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new Vn(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2D=function(t,e,n){var r;return Ut.get("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Jn(n),this.compileAndRun(r,[t,e],this.makePackedTensor(n.outShape,t.dtype))):(r=new Yn(n),this.compileAndRun(r,[t,e]))},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Kn(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Hn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3d=function(t,e,n){var r=new Xn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerInput=function(t,e,n){var r=new Gn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerFilter=function(t,e,n){var r=new qn(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new Fi(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},t.prototype.avgPool=function(t,e){var n=new Fi(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.maxPoolBackprop=function(t,e,n,r){var i=new Fi(r,"max",!0),o=this.compileAndRun(i,[e]),a=new Ti(r),s=this.makeOutputArray(a.outputShape,e.dtype),u=this.compileAndRun(a,[t,o],s);return o.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new In(n),i=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],i)},t.prototype.cast=function(t,e){return Ke(t,e,this)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,o=0;o<t.rank;o++)o!==e&&(r[i++]=t.shape[o]);var a=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(o=0;o<u.length;o++)a[e]=o,u[o]=this.slice(t,a,s).reshape(r);return u},t.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);return!n.isPacked||ti(t.shape,e)||null!==n.texture&&ti(n.shape,e)?$e(t,e):this.packedReshape(t,e)},t.prototype.resizeBilinear=function(t,e,n,r){var i=Ut.get("WEBGL_PACK_IMAGE_OPERATIONS")?new Wi(t.shape,e,n,r):new Ui(t.shape,e,n,r);return this.compileAndRun(i,[t])},t.prototype.resizeBilinearBackprop=function(t,e,n){var r=new Bi(t,e,n);return this.compileAndRun(r,[t])},t.prototype.resizeNearestNeighbor=function(t,e,n,r){var i=new ji(t.shape,e,n,r);return this.compileAndRun(i,[t])},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new Vi(t,e,n);return this.compileAndRun(r,[t])},t.prototype.multinomial=function(t,e,n,r){var i=e?t:Ee(t),o=i.shape[0],a=i.shape[1],s=new Di(o,a,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[i],u,l)},t.prototype.oneHot=function(t,e,n,r){var i=new Oi(t.size,e,n,r);return this.compileAndRun(i,[t])},t.prototype.nonMaxSuppression=function(t,e,n,r,i){return Yt("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Qe(t.dataSync(),e.dataSync(),n,r,i)},t.prototype.cropAndResize=function(t,e,n,r,i,o){var a=new Zn(t.shape,e.shape,r,i,o);return this.compileAndRun(a,[t,e,n])},t.prototype.depthToSpace=function(t,e,n){d(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],i="NHWC"===n?t.shape[1]:t.shape[2],o="NHWC"===n?t.shape[2]:t.shape[3],a="NHWC"===n?t.shape[3]:t.shape[1],s=i*e,u=o*e,l=a/(e*e),c=new er("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},t.prototype.split=function(t,e,n){return en(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=de(0,t,n),i=r.sliceRank,o=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/a,a],c=t.reshape([o,i]),p=e.reshape([o,a]);if(0===u)return $e(Re([]),n);var h=De(0),f=new Gi(o,i,c.rank,p.rank,s,l);return this.compileAndRun(f,[p,c,h]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var i=de(0,t,n),o=i.sliceRank,a=i.numUpdates,s=i.strides,u=i.outputSize,l=new Gi(a,o,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},t.prototype.fft=function(t){return this.fftImpl(t,!1)},t.prototype.ifft=function(t){return this.fftImpl(t,!0)},t.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new or(rr,t.shape,e),i=new or(ir,t.shape,e),o=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],a=this.compileAndRun(r,o),s=this.compileAndRun(i,o),u=this.complex(a,s).as2D(t.shape[0],t.shape[1]);return a.dispose(),s.dispose(),u},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=ce(t,e),o=i[0],a=i[1],s=i[2],u=i[3],l=e.reshape([a,r]),c=t.reshape([t.size/s,s]),p=new pr(r,u,[a,s]);return this.compileAndRun(p,[c,l]).reshape(o)},t.prototype.fill=function(t,e,n){if("string"===(n=n||B(e))){var r=T(n,v(t));return r.fill(e),lt.make(t,{values:r},n)}var i=new ar(t,e),o=i.getCustomSetupFunc(e),a=this.makeOutputArray(t,n);return this.compileAndRun(i,[],a,o)},t.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},t.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},t.prototype.makeOutputArray=function(t,e){return lt.make(t,{},e,this)},t.prototype.makePackedTensor=function(t,e){var n=lt.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},t.prototype.unpackTensor=function(t){var e=new xo(t.shape);return this.compileAndRun(e,[t],lt.make(e.outputShape,{},t.dtype,this))},t.prototype.packTensor=function(t){var e=new _i(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype))},t.prototype.packedReshape=function(t,e){var n=t.reshape([Yr(t.shape)].concat(Jr(t.shape))),r=[Yr(e)].concat(Jr(e)),i=new Pi(r,n.shape);return this.compileAndRun(i,[n]).reshape(e)},t.prototype.compileAndRun=function(t,e,n,r,i){var o=this;if(void 0===i&&(i=!0),null==n&&(n=t.usesPackedTextures?this.makePackedTensor(t.outputShape,e[0].dtype):this.makeOutputArray(t.outputShape,e[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=A(n.dtype,0),n;var a=e.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=o.texData.get(e.dataId);if(null==n.texture){if(!t.usesPackedTextures&&v(e.shape)<=Ut.get("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:o.readSync(e.dataId)};t.usesPackedTextures&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.usesPackedTextures)e=n.isPacked?o.unpackTensor(e):o.packTensor(e),n=o.texData.get(e.dataId);else if(n.isPacked&&!ti(n.shape,e.shape)){var r=e,i=e.shape;e.shape=n.shape,e=o.packedReshape(e,i),n=o.texData.get(e.dataId),r.shape=i}return o.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}});this.uploadToGPU(n.dataId);var s,u={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},l=function(t,e,n){var r="";e.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e});var i=t.userCode;return t.constructor.name+"_"+r+"_"+i}(t,a,u),c=this.getAndSaveBinary(l,function(){return function(t,e,n,r){for(var i=e.userCode,o=n.map(function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}}),a=o.map(function(t){return t.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=fn(o,s,i,e.usesPackedTextures),l=t.createProgram(u),c={},p=0;p<e.variableNames.length;p++){var h=e.variableNames[p];c[h]=t.getUniformLocation(l,h,!1),c["offset"+h]=t.getUniformLocation(l,"offset"+h,!1)}return{program:e,source:u,webGLProgram:l,uniformLocations:c,gpgpu:t,inShapeInfos:a,outShapeInfo:s}}(o.gpgpu,t,a,u)}),p=null!=this.activeTimers;p&&(s=this.startTimer()),function(t,e,n,r){Ei(t.inShapeInfos,e),Ei([t.outShapeInfo],[n]);var i=n.texData.texture,o=n.texData.texShape,a=t.gpgpu;n.texData.isPacked?a.setOutputPackedMatrixTexture(i,o[0],o[1]):a.setOutputMatrixTexture(i,o[0],o[1]),a.setProgram(t.webGLProgram),e.forEach(function(e,n){var r=t.program.variableNames[n],i=t.uniformLocations[r],o=t.uniformLocations["offset"+r];if(null!=i)if(e.isUniform)if(1===v(e.shape))a.gl.uniform1f(i,e.uniformValues[0]);else{var s=e.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),a.gl.uniform1fv(i,s)}else null!=e.texData.slice&&null!=o&&a.gl.uniform1i(o,e.texData.slice.flatOffset),a.setInputMatrixTexture(e.texData.texture,i,n)}),null!=r&&r(a,t.webGLProgram),a.executeProgram()}(c,a,u,r);var h=1024*Ut.get("WEBGL_NUM_MB_BEFORE_PAGING");if(i&&this.numBytesInGPU>h)for(var f=this.numBytesInGPU-h;f>0&&this.lruDataGPU.length>0;){var d=this.lruDataGPU.shift(),m=this.texData.get(d),g=m.texShape,y=m.dtype;f-=this.computeBytes(g,y),this.read(d)}return p&&(s=this.endTimer(s),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(s)})),Ut.get("WEBGL_LAZILY_UNPACK")||!this.texData.get(n.dataId).isPacked||t.isPackShader?n:this.unpackTensor(n)},t.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){if(!this.disposed){for(var t in this.binaryCache)this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram);this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixels2DContext&&this.fromPixels2DContext.canvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0}},t.prototype.floatPrecision=function(){var t=this;return Gt(function(){var e=Ut.get("DEBUG");Ut.set("DEBUG",!1);var n=t.abs(De(1e-8)).dataSync()[0];return Ut.set("DEBUG",e),n>0?32:16})},t.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,i=n.dtype,o=n.values,a=n.texture,s=n.usage,u=n.isPacked;if(null==a){var l,c=null!=this.activeTimers;c&&(l=performance.now());var p=Zr(r,u);n.texShape=p;var h=this.acquireTexture(t,p,s,i,u);if(n.texture=h,null!=o){if(u){var f=Yr(r),d=1,m=1;r.length&&(d=(e=Jr(r))[0],m=e[1]),this.gpgpu.uploadMatrixToPackedTexture(h,f,d,m,p[0],p[1],fa(o))}else this.gpgpu.uploadMatrixToTexture(h,p[0],p[1],fa(o));n.values=null,c&&(this.uploadWaitMs+=performance.now()-l)}}else Ut.get("WEBGL_NUM_MB_BEFORE_PAGING")<Number.POSITIVE_INFINITY&&this.lruDataGPU.indexOf(t)>=0&&(this.lruDataGPU.splice(this.lruDataGPU.indexOf(t),1),this.lruDataGPU.push(t))},t.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.texture,i=n.texShape,o=n.dtype,a=n.usage,s=n.isPacked;return null!=r&&(this.releaseTexture(t,r,i,a,o,s),n.texture=null,n.texShape=null,n.isPacked=!1),n.usage=lr.UPLOAD,null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r<n.length;++r)n[r]=Math.round(t[r]);return n}throw new Error("Unknown dtype "+e)}(e,o)),n.values},t.prototype.releaseTexture=function(t,e,n,r,i,o){if(Ut.get("WEBGL_NUM_MB_BEFORE_PAGING")<Number.POSITIVE_INFINITY){var a=this.lruDataGPU.indexOf(t);a>=0&&this.lruDataGPU.splice(a,1)}this.numBytesInGPU-=this.computeBytes(n,i),this.textureManager.releaseTexture(e,n,r,o)},t.prototype.acquireTexture=function(t,e,n,r,i){return Ut.get("WEBGL_NUM_MB_BEFORE_PAGING")<Number.POSITIVE_INFINITY&&this.lruDataGPU.push(t),this.numBytesInGPU+=this.computeBytes(e,r),this.textureManager.acquireTexture(e,n,i)},t.prototype.computeBytes=function(t,e){return t[0]*t[1]*M(e)},t}();function fa(t){return t instanceof Float32Array?t:new Float32Array(t)}Ut.get("IS_BROWSER")&&Ut.registerBackend("webgl",function(){return new ha},2);var da=Ce({abs_:function(t){var e=Ne(t,"x","abs");return"complex64"===e.dtype?Ut.engine.runKernel(function(t){return t.complexAbs(e)},{$x:e}):Ut.engine.runKernel(function(t){return t.abs(e)},{$x:e},function(t){return{$x:function(){return t.mulStrict(e.toFloat().step(-1))}}})}}),ma=Ce({acos_:function(t){var e=Ne(t,"x","acos");return Ut.engine.runKernel(function(t){return t.acos(e)},{$x:e},function(t){return{$x:function(){return t.divStrict(De(1).sub(e.toFloat().square()).sqrt()).neg()}}})}}),ga=Ce({acosh_:function(t){var e=Ne(t,"x","acosh");return Ut.engine.runKernel(function(t){return t.acosh(e)},{$x:e},function(t){return{$x:function(){return t.divStrict(e.toFloat().square().sub(1).sqrt())}}})}}),ya=Ce({asin_:function(t){var e=Ne(t,"x","asin");return Ut.engine.runKernel(function(t){return t.asin(e)},{$x:e},function(t){return{$x:function(){return t.divStrict(De(1).sub(e.toFloat().square()).sqrt())}}})}}),va=Ce({asinh_:function(t){var e=Ne(t,"x","asinh");return Ut.engine.runKernel(function(t){return t.asinh(e)},{$x:e},function(t){return{$x:function(){return t.divStrict(De(1).add(e.toFloat().square()).sqrt())}}})}}),ba=Ce({atan_:function(t){var e=Ne(t,"x","atan");return Ut.engine.runKernel(function(t){return t.atan(e)},{$x:e},function(t){return{$x:function(){return t.div(e.toFloat().square().add(1))}}})}}),wa=Ce({atanh_:function(t){var e=Ne(t,"x","atanh");return Ut.engine.runKernel(function(t){return t.atanh(e)},{$x:e},function(t){return{$x:function(){return t.div(De(1).sub(e.toFloat().square()))}}})}}),xa=Ce({ceil_:function(t){var e=Ne(t,"x","ceil");return Ut.engine.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return qe(t)}}})}}),Na=Ce({clipByValue_:function(t,e,n){var r=Ne(t,"x","clipByValue");return d(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),Ut.engine.runKernel(function(t){return t.clip(r,e,n)},{$x:r},function(t){return{$x:function(){return t.where(r.greaterEqual(e).logicalAnd(r.lessEqual(n)),qe(t))}}})}}),Sa=Ce({cos_:function(t){var e=Ne(t,"x","cos");return Ut.engine.runKernel(function(t){return t.cos(e)},{$x:e},function(t){return{$x:function(){return e.toFloat().sin().neg().mulStrict(t)}}})}}),Ca=Ce({cosh_:function(t){var e=Ne(t,"x","cosh");return Ut.engine.runKernel(function(t){return t.cosh(e)},{$x:e},function(t){return{$x:function(){return e.toFloat().sinh().mulStrict(t)}}})}}),Ea=Ce({erf_:function(t){var e=Ne(t,"x","erf");return d("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),Ut.engine.runKernel(function(t){return t.erf(e)},{$x:e},function(t){return{$x:function(){return t.mul(e.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),Ia=Ce({exp_:function(t){var e=Ne(t,"x","exp");return Ut.engine.runKernel(function(t,n){return n(t.exp(e))},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n)}}})}}),ka=Ce({expm1_:function(t){var e=Ne(t,"x","expm1");return Ut.engine.runKernel(function(t){return t.expm1(e)},{$x:e},function(t){return{$x:function(){return t.mulStrict(e.exp())}}})}}),Aa=Ce({floor_:function(t){var e=Ne(t,"x","floor");return Ut.engine.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return qe(t)}}})}}),Ta=Ce({log_:function(t){var e=Ne(t,"x","log");return Ut.engine.runKernel(function(t){return t.log(e)},{$x:e},function(t){return{$x:function(){return t.divStrict(e.toFloat())}}})}}),Ra=Ce({log1p_:function(t){var e=Ne(t,"x","log1p");return Ut.engine.runKernel(function(t){return t.log1p(e)},{$x:e},function(t){return{$x:function(){return t.div(e.add(1))}}})}}),Da=Ce({logSigmoid_:function(t){var e=Ne(t,"x","logSigmoid");return Ut.engine.runKernel(function(t){return t.softplus(e.neg()).neg()},{$x:e},function(t){return{$x:function(){return t.mulStrict(e.neg().sigmoid())}}})}}),Oa=Ce({neg_:function(t){var e=Ne(t,"x","neg");return Ut.engine.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),_a=Ce({reciprocal_:function(t){var e=Ne(t,"x","reciprocal");return Ut.engine.runKernel(function(t){return t.reciprocal(e)},{$x:e},function(t){return{$x:function(){return t.divStrict(e.square().neg())}}})}}),Ma=Ce({round_:function(t){var e=Ne(t,"x","round");return Ut.engine.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return qe(t)}}})}}),La=Ce({rsqrt_:function(t){var e=Ne(t,"x","rsqrt");return Ut.engine.runKernel(function(t){return t.rsqrt(e)},{$x:e},function(t){return{$x:function(){return t.div(e.pow(1.5).mul(2)).neg()}}})}}),Fa=Ce({sigmoid_:function(t){var e=Ne(t,"x","sigmoid");return Ut.engine.runKernel(function(t,n){return n(t.sigmoid(e))},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.mul(De(1).sub(n)))}}})}}),za=Ce({sign_:function(t){var e=Ne(t,"x","sign");return Ut.engine.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return qe(t)}}})}}),Pa=Ce({sin_:function(t){var e=Ne(t,"x","sin");return Ut.engine.runKernel(function(t){return t.sin(e)},{$x:e},function(t){return{$x:function(){return e.toFloat().cos().mulStrict(t)}}})}}),Ba=Ce({sinh_:function(t){var e=Ne(t,"x","sinh");return Ut.engine.runKernel(function(t){return t.sinh(e)},{$x:e},function(t){return{$x:function(){return e.toFloat().cosh().mulStrict(t)}}})}}),Ua=Ce({softplus_:function(t){var e=Ne(t,"x","softplus");return Ut.engine.runKernel(function(t){return t.softplus(e)},{$x:e},function(t){return{$x:function(){return t.mulStrict(e.sigmoid())}}})}}),Wa=Ce({sqrt_:function(t){var e=Ne(t,"x","sqrt");return Ut.engine.runKernel(function(t){return t.sqrt(e)},{$x:e},function(t){return{$x:function(){return t.div(e.toFloat().sqrt().mul(2))}}})}}),Va=Ce({square_:function(t){var e=Ne(t,"x","square");return Ut.engine.runKernel(function(t){return t.square(e)},{$x:e},function(t){return{$x:function(){return t.mul(e.toFloat().mul(2))}}})}}),ja=Ce({step_:function(t,e){void 0===e&&(e=0);var n=Ne(t,"x","step");return Ut.engine.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return qe(t)}}})}}),qa=Ce({tan_:function(t){var e=Ne(t,"x","tan");return Ut.engine.runKernel(function(t){return t.tan(e)},{$x:e},function(t){return{$x:function(){return t.divStrict(e.cos().square())}}})}}),Ga=Ce({tanh_:function(t){var e=Ne(t,"x","tanh");return Ut.engine.runKernel(function(t,n){return n(t.tanh(e))},{$x:e},function(t,e){var n=e[0];return{$x:function(){return De(1).sub(n.square()).mulStrict(t)}}})}});function Ha(t,e,n,r,i,o){var a,s,u=Ne(t,"x","batchNorm"),l=Ne(e,"mean","batchNorm"),c=Ne(n,"variance","batchNorm");return null!=i&&(a=Ne(i,"scale","batchNorm")),null!=r&&(s=Ne(r,"offset","batchNorm")),d(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),d(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."}),d(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=a&&d(2===a.rank||1===a.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+a.rank+"."}),null!=s&&d(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),Xa(u,l,c,s,a,o)}function Ka(t,e,n,r,i,o){var a,s,u=Ne(t,"x","batchNorm"),l=Ne(e,"mean","batchNorm"),c=Ne(n,"variance","batchNorm");return null!=i&&(a=Ne(i,"scale","batchNorm")),null!=r&&(s=Ne(r,"offset","batchNorm")),d(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),d(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."}),d(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=a&&d(3===a.rank||1===a.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+a.rank+"."}),null!=s&&d(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),Xa(u,l,c,s,a,o)}function $a(t,e,n,r,i,o){var a,s,u=Ne(t,"x","batchNorm"),l=Ne(e,"mean","batchNorm"),c=Ne(n,"variance","batchNorm");return null!=i&&(a=Ne(i,"scale","batchNorm")),null!=r&&(s=Ne(r,"offset","batchNorm")),d(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),d(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."}),d(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=a&&d(4===a.rank||1===a.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+a.rank+"."}),null!=s&&d(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),Xa(u,l,c,s,a,o)}function Xa(t,e,n,r,i,o){null==o&&(o=.001);var a,s,u,l=Ne(t,"x","batchNorm"),c=Ne(e,"mean","batchNorm"),p=Ne(n,"variance","batchNorm");return null!=i&&(a=Ne(i,"scale","batchNorm")),null!=r&&(s=Ne(r,"offset","batchNorm")),d(c.rank===p.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),d(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),d(null==a||c.rank===a.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,Ut.engine.runKernel(function(t){return t.batchNormalization(u,Ya(c),Ya(p),o,Ya(a),Ya(s))},{$x:l,$mean:c,$variance:p,$scale:a,$offset:s},function(t){var e=null==a?De(1):a,n=un(c.shape,u.shape),r=[];if(1===c.rank){for(var i=0;i<u.shape.length-1;++i)r.push(u.shape[i]);r.push(1)}var s=l.sub(c),h=t.mul(e),f=La(p.add(De(o))),d=f.mul(f).mul(f).mul(De(-.5));return{$x:function(){return 1===c.rank?t.mul(sa(f.as4D(1,1,1,c.shape[0]),r)).mul(e).reshape(l.shape):t.mul(f).mul(e).reshape(l.shape)},$mean:function(){var t=f.mul(De(-1)).mul(h);return 1===c.rank&&(t=t.sum(n)),t.reshape(c.shape)},$variance:function(){var t=d.mul(s).mul(h);return 1===c.rank&&(t=t.sum(n)),t.reshape(c.shape)},$scale:function(){var e=s.mul(f),r=t.mul(e);return 1===c.rank&&(r=r.sum(n)),r.reshape(c.shape)},$offset:function(){var e=t;return 1===c.rank&&(e=e.sum(n)),e.reshape(c.shape)}}}).reshape(l.shape)}function Ya(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t}function Ja(){Bt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var Za=Ce({batchNormalization2d_:function(t,e,n,r,i,o){return void 0===r&&(r=.001),Ja(),Ha(t,e,n,o,i,r)}}),Qa=Ce({batchNormalization3d_:function(t,e,n,r,i,o){return void 0===r&&(r=.001),Ja(),Ka(t,e,n,o,i,r)}}),ts=Ce({batchNormalization4d_:function(t,e,n,r,i,o){return void 0===r&&(r=.001),Ja(),$a(t,e,n,o,i,r)}}),es=Ce({batchNormalization_:function(t,e,n,r,i,o){return void 0===r&&(r=.001),Ja(),Xa(t,e,n,o,i,r)}}),ns=Ce({batchNorm_:Xa}),rs=Ce({batchNorm2d_:Ha}),is=Ce({batchNorm3d_:Ka}),os=Ce({batchNorm4d_:$a});function as(t,e,n,r,i,o,a){void 0===a&&(a="channelsLast");var s,u=ls(e),l=u[0],c=u[1];if("channelsLast"===a)s=[l,c,t[3],t[3]];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);s=[l,c,t[1],t[1]]}return ss(t,s,n,r,i,o,!1,a)}function ss(t,e,n,r,i,o,a,s){void 0===a&&(a=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],l=u[0],c=u[1],p=u[2],h=u[3];if("channelsLast"===s)l=t[0],c=t[1],p=t[2],h=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);l=t[0],h=t[1],c=t[2],p=t[3]}var f,m=e[0],g=e[1],y=e[3],v=ls(n),b=v[0],x=v[1],N=ls(r),S=N[0],C=N[1],E=ps(m,S),I=ps(g,C),k=function(t,e,n,r,i,o,a,s){var u,l,c;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var p=function(t,e,n,r,i,o){null==i&&(i=function(t,e,n,r){void 0===r&&(r=1);var i=ps(e,r);return Math.floor((t[0]*(n-1)-n+i)/2)}(t,e,r));var a=t[0],s=t[1],u=hs((a-e+2*i)/r+1,o);d(w(u),function(){return"The output # of rows ("+u+") must be an integer. Change the stride and/or zero pad parameters"});var l=hs((s-e+2*i)/r+1,o);return d(w(l),function(){return"The output # of columns ("+l+") must be an integer. Change the stride and/or zero pad parameters"}),[u,l,n]}([e,n,1],o,1,r,t,s);l=p[0],c=p[1]}else if("same"===t){l=Math.ceil(e/r),c=Math.ceil(n/i);var h=Math.max(0,(l-1)*r+o-e),f=Math.max(0,(c-1)*i+a-n),m=Math.floor(h/2),g=h-m,y=Math.floor(f/2);u={top:m,bottom:g,left:y,right:f-y,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((e-o+1)/r),c=Math.ceil((n-a+1)/i)}return{padInfo:u,outHeight:l,outWidth:c}}(i,c,p,b,x,E,I,o),A=k.padInfo,T=k.outHeight,R=k.outWidth,D=a?y*h:y;return"channelsFirst"===s?f=[l,D,T,R]:"channelsLast"===s&&(f=[l,T,R,D]),{batchSize:l,dataFormat:s,inHeight:c,inWidth:p,inChannels:h,outHeight:T,outWidth:R,outChannels:D,padInfo:A,strideHeight:b,strideWidth:x,filterHeight:m,filterWidth:g,effectiveFilterHeight:E,effectiveFilterWidth:I,dilationHeight:S,dilationWidth:C,inShape:t,outShape:f,filterShape:e}}function us(t,e,n,r,i,o,a){void 0===o&&(o=!1),void 0===a&&(a="channelsLast");var s=[-1,-1,-1,-1,-1],u=s[0],l=s[1],c=s[2],p=s[3],h=s[4];if("channelsLast"===a)u=t[0],l=t[1],c=t[2],p=t[3],h=t[4];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);u=t[0],h=t[1],l=t[2],c=t[3],p=t[4]}var f,d=e[0],m=e[1],g=e[2],y=e[4],v=cs(n),b=v[0],w=v[1],x=v[2],N=cs(r),S=N[0],C=N[1],E=N[2],I=function(t,e,n,r,i,o,a,s,u,l){var c,p,h,f;if("same"===t){var d=((p=Math.ceil(e/i))-1)*i+s-e,m=((h=Math.ceil(n/o))-1)*o+u-n,g=((f=Math.ceil(r/a))-1)*a+l-r,y=Math.floor(d/2),v=d-y,b=Math.floor(m/2),w=m-b,x=Math.floor(g/2);c={top:b,bottom:w,left:x,right:g-x,front:y,back:v,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);c={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((e-s+1)/i),h=Math.ceil((n-u+1)/o),f=Math.ceil((r-l+1)/a)}return{padInfo:c,outDepth:p,outHeight:h,outWidth:f}}(i,l,c,p,b,w,x,ps(d,S),ps(m,C),ps(g,E)),k=I.padInfo,A=I.outDepth,T=I.outHeight,R=I.outWidth,D=o?y*h:y;return"channelsFirst"===a?f=[u,D,A,T,R]:"channelsLast"===a&&(f=[u,A,T,R,D]),{batchSize:u,dataFormat:a,inDepth:l,inHeight:c,inWidth:p,inChannels:h,outDepth:A,outHeight:T,outWidth:R,outChannels:D,padInfo:k,strideDepth:b,strideHeight:w,strideWidth:x,filterDepth:d,filterHeight:m,filterWidth:g,dilationDepth:S,dilationHeight:C,dilationWidth:E,inShape:t,outShape:f,filterShape:e}}function ls(t){return"number"==typeof t?[t,t]:t}function cs(t){return"number"==typeof t?[t,t,t]:t}function ps(t,e){return e<=1?t:t+(t-1)*(e-1)}function hs(t,e){if(!e)return t;switch(e){case"round":return Math.round(t);case"ceil":return Math.ceil(t);case"floor":return Math.floor(t);default:throw new Error("Unknown roundingMode "+e)}}function fs(t){var e=ls(t),n=e[0],r=e[1];return 1===n&&1===r}function ds(t,e){return fs(t)||fs(e)}function ms(t,e,n,r,i,o){d(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var a=t,s=e,u=!1;3===e.rank&&(u=!0,s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),a=[1,t[0],t[1],t[2]]);var l=a[3],c=s.shape[3];d(4===a.length,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+a.length+"."}),d(4===s.rank,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+s.rank}),d(4===n.rank,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank}),d(l===n.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."}),d(c===n.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[3]+"."}),null!=o&&d(w(i),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var p=ss(a,n.shape,r,1,i,o),h=Ut.engine.runKernel(function(t){return t.conv2dDerInput(s,n,p)},{dy4D:s,filter:n},function(t){return{dy4D:function(){return bs(t,n,r,i,"NHWC",1,o)},filter:function(){return xs(t,s,n.shape,r,i,o)}}});return u?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function gs(t,e,n,r,i,o){var a=t;3===t.rank&&(a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var s=e;3===s.rank&&(s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),d(4===a.rank,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+a.shape+"."}),d(4===s.rank,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+s.shape+"."}),d(4===n.length,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."}),d(a.shape[3]===n[2],function(){return"Error in conv2dDerFilter: depth of input "+a.shape[3]+") must match input depth in filter ("+n[2]+"."}),d(s.shape[3]===n[3],function(){return"Error in conv2dDerFilter: depth of dy ("+s.shape[3]+") must match output depth for filter ("+n[3]+")."}),null!=o&&d(w(i),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var u=ss(a.shape,n,r,1,i,o);return Ut.engine.runKernel(function(t){return t.conv2dDerFilter(a,s,u)},{x4D:a,dy4D:s})}function ys(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t),n=e[0],r=e[1],i=e[2];return 1===n&&1===r&&1===i}var vs=Ce({conv1d_:function(t,e,n,r,i,o,a){void 0===i&&(i="NWC"),void 0===o&&(o=1);var s=Ne(t,"x","conv1d"),u=Ne(e,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),d(3===l.rank,function(){return"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."}),d(3===u.rank,function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."}),null!=a&&d(w(r),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}),d(l.shape[2]===u.shape[1],function(){return"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+"."}),d(ds(n,o),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+o+"'"}),d("NWC"===i,function(){return"Error in conv1d: got dataFormat of "+i+" but only NWC is currently supported."});var p=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),h=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),f=bs(h,p,[1,n],r,"NHWC",[1,o],a);return c?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3])}}),bs=Ce({conv2d_:function(t,e,n,r,i,o,a){void 0===i&&(i="NHWC"),void 0===o&&(o=[1,1]);var s=Ne(t,"x","conv2d"),u=Ne(e,"filter","conv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,function(){return"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."}),d(4===u.rank,function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."}),null!=a&&d(w(r),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."}),d(l.shape[3]===u.shape[2],function(){return"Error in conv2d: depth of input ("+l.shape[3]+") must match input depth for filter "+u.shape[2]+"."}),d(ds(n,o),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),d("NHWC"===i,function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."});var p=ss(l.shape,u.shape,n,o,r,a),h=Ut.engine.runKernel(function(t){return t.conv2d(l,u,p)},{x:l,$filter:u},function(t){return d(fs(o),function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"}),{x:function(){return ms(l.shape,t,u,n,r)},$filter:function(){return gs(l,t,u.shape,n,r)}}});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),ws=Ce({conv3d_:function(t,e,n,r,i,o){void 0===i&&(i="NHWC"),void 0===o&&(o=[1,1,1]);var a=Ne(t,"x","conv3d"),s=Ne(e,"filter","conv3d"),u=a,l=!1;4===a.rank&&(l=!0,u=a.as5D(1,a.shape[0],a.shape[1],a.shape[2],a.shape[3])),d(5===u.rank,function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."}),d(5===s.rank,function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."}),d(u.shape[4]===s.shape[3],function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+"."}),d(function(t,e){return ys(t)||ys(e)}(n,o),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),d("NHWC"===i,function(){return"Error in conv3d: got dataFormat of "+i+" but only NHWC is currently supported."});var c=us(u.shape,s.shape,n,o,r),p=Ut.engine.runKernel(function(t){return t.conv3d(u,s,c)},{x:u,$filter:s},function(t){return d(ys(o),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+o+"'"}),{x:function(){return function(t,e,n,r,i){d(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var o=t,a=e,s=!1;4===e.rank&&(s=!0,a=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),o=[1,t[0],t[1],t[2],t[3]]);var u=o[4],l=a.shape[4];d(5===o.length,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+o.length+"."}),d(5===a.rank,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+a.rank}),d(5===n.rank,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank}),d(u===n.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."}),d(l===n.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+l+") must match output depth for filter "+n.shape[4]+"."});var c=us(o,n.shape,r,1,i),p=Ut.engine.runKernel(function(t){return t.conv3dDerInput(a,n,c)},{dy5D:a});return s?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}(u.shape,t,s,n,r)},$filter:function(){return function(t,e,n,r,i){var o=t;4===t.rank&&(o=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var a=e;4===a.rank&&(a=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),d(5===o.rank,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+o.shape+"."}),d(5===a.rank,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+a.shape+"."}),d(5===n.length,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."}),d(o.shape[4]===n[3],function(){return"Error in conv3dDerFilter: depth of input "+o.shape[4]+") must match input depth in filter ("+n[3]+"."}),d(a.shape[4]===n[4],function(){return"Error in conv3dDerFilter: depth of dy ("+a.shape[4]+") must match output depth for filter ("+n[4]+")."});var s=us(o.shape,n,r,1,i);return Ut.engine.runKernel(function(t){return t.conv3dDerFilter(o,a,s)},{x5D:o,dy5D:a})}(u,t,s.shape,n,r)}}});return l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),xs=Ce({conv2dDerFilter_:gs}),Ns=Ce({depthwiseConv2d_:function(t,e,n,r,i,o,a){void 0===i&&(i="NHWC"),void 0===o&&(o=[1,1]);var s=Ne(t,"x","depthwiseConv2d"),u=Ne(e,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."}),d(4===u.rank,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."}),d(l.shape[3]===u.shape[2],function(){return"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."}),null==o&&(o=[1,1]),d(ds(n,o),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),null!=a&&d(w(r),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+r+"."});var p=ss(l.shape,u.shape,n,o,r,a,!0),h=Ut.engine.runKernel(function(t){return t.depthwiseConv2D(l,u,p)},{x:l,$filter:u},function(t){return d(fs(o),function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"}),{x:function(){return function(t,e,n,r){var i=e,o=!1;3===e.rank&&(o=!0,i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var a=Ut.engine.runKernel(function(t){return t.depthwiseConv2DDerInput(i,n,r)},{dy4D:i});return o?a.as3D(a.shape[1],a.shape[2],a.shape[3]):a}(l.shape,t,u,p)},$filter:function(){return function(t,e,n,r){var i=t;3===t.rank&&(i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var o=e;return 3===o.rank&&(o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),Ut.engine.runKernel(function(t){return t.depthwiseConv2DDerFilter(i,o,r)},{x4D:i,dy4D:o})}(l,t,u.shape,p)}}});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),Ss=Ce({separableConv2d_:function(t,e,n,r,i,o,a){void 0===o&&(o=[1,1]),void 0===a&&(a="NHWC");var s=Ne(t,"x","separableConv2d"),u=Ne(e,"depthwiseFilter","separableConv2d"),l=Ne(n,"pointwiseFilter","separableConv2d"),c=s,p=!1;if(3===s.rank&&(p=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===a)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");d(4===c.rank,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."}),d(4===u.rank,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."}),d(4===l.rank,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."}),d(1===l.shape[0],function(){return"Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got "+l.shape[0]+"."}),d(1===l.shape[1],function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+"."});var h=u.shape[2],f=u.shape[3];d(l.shape[2]===h*f,function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+h*f+", but got "+l.shape[2]+"."});var m=Ns(c,u,r,i,a,o),g=bs(m,l,1,"valid",a);return p?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),Cs=Ce({conv2dTranspose_:function(t,e,n,r,i,o){return ms(n,Ne(t,"x","conv2dTranspose"),Ne(e,"filter","conv2dTranspose"),r,i,o)}});var Es=Ce({matMul_:function(t,e,n,r){var i;void 0===n&&(n=!1),void 0===r&&(r=!1);var o=Ne(t,"a","matMul"),a=Ne(e,"b","matMul");i=wt(o,a),o=i[0],a=i[1];var s=n?o.shape[o.rank-2]:o.shape[o.rank-1],u=r?a.shape[a.rank-1]:a.shape[a.rank-2],l=n?o.shape[o.rank-1]:o.shape[o.rank-2],c=r?a.shape[a.rank-2]:a.shape[a.rank-1],p=o.shape.slice(0,-2),h=a.shape.slice(0,-2),f=v(p),m=v(h);d(o.rank>=2&&a.rank>=2&&o.rank===a.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+a.rank+"."}),d(b(p,h),function(){return"Error in matMul: outer dimensions ("+p+") and ("+h+") of Tensors with shapes "+o.shape+" and "+a.shape+" must match."}),d(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+o.shape+" and "+a.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var g=o.shape.slice(0,-2).concat([l,c]),y=n?o.as3D(f,s,l):o.as3D(f,l,s),w=r?a.as3D(m,c,u):a.as3D(m,u,c);return Ut.engine.runKernel(function(t){return t.batchMatMul(y,w,n,r)},{$a:y,$b:w},function(t){return n||r?!n&&r?{$a:function(){return t.matMul(w,!1,!1)},$b:function(){return t.matMul(y,!0,!1)}}:n&&!r?{$a:function(){return w.matMul(t,!1,!0)},$b:function(){return y.matMul(t,!1,!1)}}:{$a:function(){return w.matMul(t,!0,!0)},$b:function(){return t.matMul(y,!0,!0)}}:{$a:function(){return t.matMul(w,!1,!0)},$b:function(){return y.matMul(t,!0,!1)}}}).reshape(g)}}),Is=Ce({dot_:function(t,e){var n=Ne(t,"t1","dot"),r=Ne(e,"t2","dot");d(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var i=1===n.rank?n.size:n.shape[1],o=1===r.rank?r.size:r.shape[0];return d(i===o,function(){return"Error in dot: inner dimensions of inputs must match, but got "+i+" and "+o+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),ks=Ce({outerProduct_:function(t,e){var n=Ne(t,"v1","outerProduct"),r=Ne(e,"v2","outerProduct");return d(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}});var As=Ce({reverse_:function(t,e){var n=Ne(t,"x","reverse");if(0===n.rank)return n.clone();var r=I(e,n.shape);return Ut.engine.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),Ts=Ce({reverse1d_:function(t){var e=Ne(t,"x","reverse");return d(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),As(e,0)}}),Rs=Ce({reverse2d_:function(t,e){var n=Ne(t,"x","reverse");return d(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),As(n,e)}}),Ds=Ce({reverse3d_:function(t,e){var n=Ne(t,"x","reverse");return d(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),As(n,e)}}),Os=Ce({reverse4d_:function(t,e){var n=Ne(t,"x","reverse");return d(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),As(n,e)}});function _s(t,e,n,r,i,o){var a=Ne(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==r&&(r=[1,1]),d(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),d(ds(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=o&&d(w(i),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var l=as(s.shape,e,n,r,i,o),c=Ut.engine.runKernel(function(t,e){return e(t.maxPool(s,l))},{x:s},function(t,o){var a=o[0];return{x:function(){return function(t,e,n,r,i,o,a,s){var u=Ne(t,"dy","maxPoolBackprop"),l=Ne(e,"input","maxPoolBackprop"),c=Ne(n,"output","maxPoolBackprop");d(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==o&&(o=[1,1]),d(ds(i,o),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+o+"'"}),d(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),d(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}),null!=s&&d(w(a),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+"."});var p=as(l.shape,r,i,o,a,s);return Ut.engine.runKernel(function(t){return t.maxPoolBackprop(u,l,c,p)},{$dy:u,$input:l})}(t,s,a,e,n,r,i)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function Ms(t,e,n,r,i,o){var a=Ne(t,"x","avgPool","float32");null==r&&(r=[1,1]),d(ds(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),d(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=o&&d(w(i),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var l=as(s.shape,e,n,r,i,o),c=Ut.engine.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return{x:function(){return function(t,e,n,r,i,o){var a=Ne(t,"dy","avgPoolBackprop"),s=Ne(e,"input","avgPoolBackprop");d(s.rank===a.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"}),null==i&&(i=[1,1]),d(ds(r,i),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"});var u=s,l=a,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),d(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),d(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var p=as(u.shape,n,r,i,o),h=Ut.engine.runKernel(function(t){return t.avgPoolBackprop(l,u,p)},{dy4D:l,input4D:u});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(t,s,e,n,r,i)}}});return c=c.cast(a.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var Ls=Ce({maxPool_:function(t,e,n,r,i){return _s(t,e,n,1,r,i)}}),Fs=Ce({avgPool_:function(t,e,n,r,i){return Ms(t,e,n,1,r,i)}}),zs=Ce({pool_:function(t,e,n,r,i,o){null==i&&(i=[1,1]),null==o&&(o=1),0===r&&(r="valid");var a=Ne(t,"x","maxPool"),s=a,u=!1;3===a.rank&&(u=!0,s=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),d(ds(o,i),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+i+"'"});var l,c=as(s.shape,e,o,i,r),p=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),i=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],i[e]]})}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];var h=1===p[0]&&1===p[1],f=function(t,e,n){var r=n.map(function(t){return t[0]}),i=n.map(function(t){return t[1]}),o=t.concat(r,i),a=e.map(function(t,e){return(t-o[e]%t)%t}),s=i.map(function(t,e){return t+a[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,a[e]]})]}([c.inHeight,c.inWidth],p,l),m=f[0],g=f[1],y=h?r:"valid",v=h?s:ia(s,p,m),b=("avg"===n?function(){return Ms(v,e,o,1,y)}:function(){return _s(v,e,o,1,y)})(),w=h?b:Uo(b,p,g);return u?w.as3D(w.shape[1],w.shape[2],w.shape[3]):w}});var Ps=Ce({slice_:function(t,e,n){var r,i,o=Ne(t,"x","slice");if(0===o.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof e?[e].concat(new Array(o.rank-1).fill(0)):e.length<o.rank?e.concat(new Array(o.rank-e.length).fill(0)):e.slice(),i=(i=null==n?new Array(o.rank).fill(-1):"number"==typeof n?[n].concat(new Array(o.rank-1).fill(-1)):n.length<o.rank?n.concat(new Array(o.rank-n.length).fill(-1)):n).map(function(t,e){return t>=0?t:(d(-1===t,function(){return"Bad value in size"}),o.shape[e]-r[e])}),function(t,e,n){d(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),d(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){d(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},i=0;i<t.rank;++i)r(i)}(o,r,i);var a=o.shape;return Ut.engine.runKernel(function(t){return t.slice(o,r,i)},{$x:o},function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],a[n]-r[n]-i[n]]);return{$x:function(){return t.pad(e)}}})}}),Bs=Ce({slice1d_:function(t,e,n){var r=Ne(t,"x","slice1d");return d(1===r.rank,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"}),Ps(r,[e],[n])}}),Us=Ce({slice2d_:function(t,e,n){var r=Ne(t,"x","slice2d");return d(2===r.rank,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"}),Ps(r,e,n)}}),Ws=Ce({slice3d_:function(t,e,n){var r=Ne(t,"x","slice3d");return d(3===r.rank,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"}),Ps(r,e,n)}}),Vs=Ce({slice4d_:function(t,e,n){var r=Ne(t,"x","slice4d");return d(4===r.rank,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"}),Ps(r,e,n)}});function js(t,e,n,r,i){var o=e[0];return o.rank<n.rank&&(o=o.reshape(ie(o.shape,r))),t.rank<n.rank&&(t=t.reshape(ie(t.shape,r))),{$x:function(){var e=t.mul(n.equal(o).cast(t.dtype));return null==i?e:e.transpose(i)}}}var qs=Ce({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","all","bool"),i=I(e,r.shape),o=i,a=ae(o,r.rank);null!=a&&(r=r.transpose(a),o=ue(o.length,r.rank));var s=Ut.engine.runKernel(function(t){return t.all(r,o)},{$x:r});if(n){var u=ie(s.shape,i);return s.reshape(u)}return s}}),Gs=Ce({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","any","bool"),i=I(e,r.shape),o=i,a=ae(o,r.rank);null!=a&&(r=r.transpose(a),o=ue(o.length,r.rank));var s=Ut.engine.runKernel(function(t){return t.any(r,o)},{$x:r});if(n){var u=ie(s.shape,i);return s.reshape(u)}return s}}),Hs=Ce({argMax_:function(t,e){void 0===e&&(e=0);var n=Ne(t,"x","argMax");null==e&&(e=0);var r=I(e,n.shape),i=ae(r,n.rank);return null!=i&&(n=n.transpose(i),r=ue(r.length,n.rank)),Ut.engine.runKernel(function(t){return t.argMax(n,r[0])},{$x:n},function(t){return{$x:function(){return qe(n)}}})}}),Ks=Ce({argMin_:function(t,e){void 0===e&&(e=0);var n=Ne(t,"x","argMin");null==e&&(e=0);var r=I(e,n.shape),i=ae(r,n.rank);return null!=i&&(n=n.transpose(i),r=ue(r.length,n.rank)),Ut.engine.runKernel(function(t){return t.argMin(n,r[0])},{$x:n},function(t){return{$x:function(){return qe(n)}}})}}),$s=Ce({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","logSumExp"),i=I(e,r.shape),o=r.max(i,!0),a=r.sub(o).exp().sum(i).log(),s=o.reshape(a.shape).add(a);if(n){var u=ie(s.shape,i);return s.reshape(u)}return s}}),Xs=Ce({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","max"),i=r,o=I(e,r.shape),a=o,s=ae(a,r.rank);null!=s&&(r=r.transpose(s),a=ue(a.length,r.rank));var u=Ut.engine.runKernel(function(t,e){return e(t.max(r,a))},{$x:r},function(t,e){return js(t,e,i,o,s)});if(n){var l=ie(u.shape,o);u=u.reshape(l)}return u}}),Ys=Ce({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","mean"),i=I(e,r.shape),o=v(re(r.shape,i)[1]);return jt(function(t){var r=De(o);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return i.forEach(function(t){n[t]=1}),e.reshape(n).mul(Pe(t.shape,"float32")).div(r)}}})(r)}}),Js=Ce({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","min"),i=r,o=I(e,r.shape),a=o,s=ae(a,r.rank);null!=s&&(r=r.transpose(s),a=ue(a.length,r.rank));var u=Ut.engine.runKernel(function(t,e){return e(t.min(r,a))},{$x:r},function(t,e){return js(t,e,i,o,s)});if(n){var l=ie(u.shape,o);u=u.reshape(l)}return u}}),Zs=Ce({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=I(e,(t=Ne(t,"x","moments")).shape),i=t.mean(r,n),o=i.shape;return n||(o=ie(i.shape,r)),{mean:i,variance:t.toFloat().sub(i.reshape(o)).square().mean(r,n)}}}),Qs=Ce({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var i=I(e,r.shape);return jt(function(t){var e=ae(i,t.rank),r=i,o=t;null!=e&&(o=t.transpose(e),r=ue(r.length,t.rank));var a=Ut.engine.runKernel(function(t){return t.sum(o,r)},{permutedX:o});if(n){var s=ie(a.shape,i);a=a.reshape(s)}return{value:a,gradFunc:function(e){var n=t.shape.slice();return i.forEach(function(t){n[t]=1}),e.reshape(n).mul(Pe(t.shape,"float32"))}}})(r)}}),tu=Ce({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ne(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var i=I(e,r.shape),o=ae(i,r.rank),a=i,s=r;null!=o&&(s=r.transpose(o),a=ue(a.length,r.rank));var u=Ut.engine.runKernel(function(t){return t.prod(s,a)},{permutedX:s});if(n){var l=ie(u.shape,i);u=u.reshape(l)}return u}});var eu=Ce({equal_:function(t,e){var n,r=Ne(t,"a","equal"),i=Ne(e,"b","equal");return n=wt(r,i),r=n[0],i=n[1],ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.equal(r,i)},{$a:r,$b:i})}}),nu=Ce({equalStrict_:function(t,e){var n=Ne(t,"a","equalStrict"),r=Ne(e,"b","equalStrict");return m(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),ru=Ce({greater_:function(t,e){var n,r=Ne(t,"a","greater"),i=Ne(e,"b","greater");return n=wt(r,i),r=n[0],i=n[1],ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.greater(r,i)},{$a:r,$b:i})}}),iu=Ce({greaterEqual_:function(t,e){var n,r=Ne(t,"a","greaterEqual"),i=Ne(e,"b","greaterEqual");return n=wt(r,i),r=n[0],i=n[1],ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.greaterEqual(r,i)},{$a:r,$b:i},function(t){return{$a:function(){return qe(r)},$b:function(){return qe(i)}}})}}),ou=Ce({greaterEqualStrict_:function(t,e){var n=Ne(t,"a","greaterEqualStrict"),r=Ne(e,"b","greaterEqualStrict");return m(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),au=Ce({greaterStrict_:function(t,e){var n=Ne(t,"a","greaterStrict"),r=Ne(e,"b","greaterStrict");return m(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),su=Ce({less_:function(t,e){var n,r=Ne(t,"a","less"),i=Ne(e,"b","less");return n=wt(r,i),r=n[0],i=n[1],ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.less(r,i)},{$a:r,$b:i})}}),uu=Ce({lessEqual_:function(t,e){var n,r=Ne(t,"a","lessEqual"),i=Ne(e,"b","lessEqual");return n=wt(r,i),r=n[0],i=n[1],ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.lessEqual(r,i)},{$a:r,$b:i})}}),lu=Ce({lessEqualStrict_:function(t,e){var n=Ne(t,"a","lessEqualStrict"),r=Ne(e,"b","lessEqualStrict");return m(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),cu=Ce({lessStrict_:function(t,e){var n=Ne(t,"a","lessStrict"),r=Ne(e,"b","lessStrict");return m(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),pu=Ce({notEqual_:function(t,e){var n,r=Ne(t,"a","notEqual"),i=Ne(e,"b","notEqual");return n=wt(r,i),r=n[0],i=n[1],ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.notEqual(r,i)},{$a:r,$b:i})}}),hu=Ce({notEqualStrict_:function(t,e){var n=Ne(t,"a","notEqualStrict"),r=Ne(e,"b","notEqualStrict");return m(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});var fu=Ce({add_:function(t,e){var n,r=Ne(t,"a","add"),i=Ne(e,"b","add");n=wt(r,i),r=n[0],i=n[1];var o=ln(r.shape,i.shape);return Ut.engine.runKernel(function(t){return t.add(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=un(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=un(i.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(i.shape)}}})}}),du=Ce({addN_:function(t){d(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),d(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return Ne(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!b(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return Ut.engine.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),mu=Ce({addStrict_:function(t,e){var n=Ne(t,"a","addStrict"),r=Ne(e,"b","addStrict");return m(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),gu=Ce({atan2_:function(t,e){var n,r=Ne(t,"a","atan2"),i=Ne(e,"b","atan2");n=wt(r,i),r=n[0],i=n[1];var o=ln(r.shape,i.shape);return Ut.engine.runKernel(function(t){return t.atan2(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=fu(r.square(),i.square()),n=t.mul(i.div(e)),a=un(r.shape,o);return a.length>0&&(n=n.sum(a)),n.reshape(r.shape)},$b:function(){var e=fu(r.square(),i.square()),n=Oa(t.mul(r.div(e))),a=un(i.shape,o);return a.length>0&&(n=n.sum(a)),n.reshape(i.shape)}}})}}),yu=Ce({div_:function(t,e){var n,r,i=Ne(t,"a","div"),o=Ne(e,"b","div");if(n=wt(i,o),i=n[0],o=n[1],"int32"===i.dtype&&"int32"===o.dtype)return bu(i,o);r=function(t){return t.realDivide(i,o)};var a=ln(i.shape,o.shape);return Ut.engine.runKernel(r,{$a:i,$b:o},function(t){return{$a:function(){var e=t.div(o.toFloat()),n=un(i.shape,a);return n.length>0?e.sum(n).reshape(i.shape):e},$b:function(){var e=t.mul(i.toFloat()),n=un(o.shape,a);n.length>0&&(e=e.sum(n).reshape(o.shape));var r=o.square();return e.div(r.toFloat()).neg()}}})}}),vu=Ce({divStrict_:function(t,e){var n=Ne(t,"a","div"),r=Ne(e,"b","div");return m(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),bu=Ce({floorDiv_:function(t,e){var n,r=Ne(t,"a","floorDiv"),i=Ne(e,"b","floorDiv");n=wt(r,i),r=n[0],i=n[1];var o=ln(r.shape,i.shape);return Ut.engine.runKernel(function(t){return t.floorDiv(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t.div(i.toFloat()),n=un(r.shape,o);return n.length>0?e.sum(n).reshape(r.shape):e},$b:function(){var e=t.mul(r.toFloat()),n=un(i.shape,o);n.length>0&&(e=e.sum(n).reshape(i.shape));var a=i.square();return e.div(a.toFloat()).neg()}}})}}),wu=Ce({maximum_:function(t,e){var n,r=Ne(t,"a","maximum"),i=Ne(e,"b","maximum");return n=wt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.maximum(r,i)},{$a:r,$b:i},function(t){return{$a:function(){return t.mul(r.greaterEqual(i).toFloat())},$b:function(){return t.mul(r.less(i).toFloat())}}})}}),xu=Ce({maximumStrict_:function(t,e){var n=Ne(t,"a","maximumStrict"),r=Ne(e,"b","maximumStrict");return m(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),Nu=Ce({minimum_:function(t,e){var n,r=Ne(t,"a","minimum"),i=Ne(e,"b","minimum");return n=wt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.minimum(r,i)},{$a:r,$b:i},function(t){return{$a:function(){return t.mul(r.lessEqual(i).toFloat())},$b:function(){return t.mul(r.greater(i).toFloat())}}})}}),Su=Ce({minimumStrict_:function(t,e){var n=Ne(t,"a","minimumStrict"),r=Ne(e,"b","minimumStrict");return m(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),Cu=Ce({mod_:function(t,e){var n,r=Ne(t,"a","mod"),i=Ne(e,"b","mod");n=wt(r,i),r=n[0],i=n[1];var o=ln(r.shape,i.shape);return Ut.engine.runKernel(function(t){return t.mod(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=un(r.shape,o);return e.length>0?t.sum(e).reshape(r.shape):t},$b:function(){var e=t.mul(r.div(i).floor().neg()),n=un(i.shape,o);return n.length>0?e.sum(n).reshape(i.shape):e}}})}}),Eu=Ce({modStrict_:function(t,e){var n=Ne(t,"a","modStrict"),r=Ne(e,"b","modStrict");return m(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),Iu=Ce({mul_:function(t,e){var n,r=Ne(t,"a","mul"),i=Ne(e,"b","mul");n=wt(r,i),r=n[0],i=n[1];var o=ln(r.shape,i.shape);return Ut.engine.runKernel(function(t){return t.multiply(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t.mul(i.toFloat()),n=un(r.shape,o);return n.length>0?e.sum(n).reshape(r.shape):e},$b:function(){var e=t.mul(r.toFloat()),n=un(i.shape,o);return n.length>0?e.sum(n).reshape(i.shape):e}}})}}),ku=Ce({mulStrict_:function(t,e){var n=Ne(t,"a","mul"),r=Ne(e,"b","mul");return m(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),Au=Ce({pow_:function(t,e){var n=Ne(t,"base","pow"),r=Ne(e,"exp","pow"),i=ln(n.shape,r.shape);return t=n.cast(vt(n.dtype,r.dtype)),e=r.cast(vt(n.dtype,r.dtype)),Ut.engine.runKernel(function(t,e){return e(t.pow(n,r))},{$base:n,$exp:r},function(t,e){var o=e[0];return{$base:function(){var e=r.toFloat(),o=t.mul(e.mul(n.pow(e.sub(De(1))))),a=un(n.shape,i);return a.length>0&&(o=o.sum(a)),o.reshape(n.shape)},$exp:function(){var e=n.greater(0),a=n.log().where(e,qe(n)),s=t.mul(o.mul(a)),u=un(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),Tu=Ce({powStrict_:function(t,e){return m(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),Ru=Ce({squaredDifference_:function(t,e){var n,r=Ne(t,"a","squaredDifference"),i=Ne(e,"b","squaredDifference");return n=wt(r,i),r=n[0],i=n[1],ln(r.shape,i.shape),Ut.engine.runKernel(function(t){return t.squaredDifference(r,i)},{$a:r,$b:i},function(t){var e=De(2);return{$a:function(){return t.mul(r.sub(i).mul(e))},$b:function(){return t.mul(i.sub(r).mul(e))}}})}}),Du=Ce({squaredDifferenceStrict_:function(t,e){var n=Ne(t,"a","squaredDifferenceStrict"),r=Ne(e,"b","squaredDifferenceStrict");return m(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),Ou=Ce({sub_:function(t,e){var n,r=Ne(t,"a","sub"),i=Ne(e,"b","sub");n=wt(r,i),r=n[0],i=n[1];var o=ln(r.shape,i.shape);return Ut.engine.runKernel(function(t){return t.subtract(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=un(r.shape,o);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=un(i.shape,o);return n.length>0&&(e=e.sum(n)),e.neg().reshape(i.shape)}}})}}),_u=Ce({subStrict_:function(t,e){var n=Ne(t,"a","subStrict"),r=Ne(e,"b","subStrict");return m(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var Mu=Ce({logicalAnd_:function(t,e){var n=Ne(t,"a","logicalAnd","bool"),r=Ne(e,"b","logicalAnd","bool");return ln(n.shape,r.shape),Ut.engine.runKernel(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),Lu=Ce({logicalNot_:function(t){var e=Ne(t,"x","logicalNot","bool");return Ut.engine.runKernel(function(t){return t.logicalNot(e)},{$x:e})}}),Fu=Ce({logicalOr_:function(t,e){var n=Ne(t,"a","logicalOr","bool"),r=Ne(e,"b","logicalOr","bool");return ln(n.shape,r.shape),Ut.engine.runKernel(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),zu=Ce({logicalXor_:function(t,e){var n=Ne(t,"a","logicalXor","bool"),r=Ne(e,"b","logicalXor","bool");return ln(n.shape,r.shape),Fu(t,e).logicalAnd(Mu(t,e).logicalNot())}}),Pu=Ce({where_:function(t,e,n){var r=Ne(e,"a","where"),i=Ne(n,"b","where"),o=Ne(t,"condition","where","bool");return m(r.shape,i.shape,"Error in where: "),1===o.rank?d(o.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):m(o.shape,i.shape,"Error in where: "),Ut.engine.runKernel(function(t){return t.select(o,r,i)},{$condition:o,$a:r,$b:i},function(t){return{$condition:function(){return qe(o).toFloat()},$a:function(){return t.mul(o.cast(t.dtype))},$b:function(){return t.mul(o.logicalNot().cast(t.dtype))}}})}}),Bu=function(t){return i(this,void 0,void 0,function(){var e,n,r;return o(this,function(i){switch(i.label){case 0:return[4,(e=Ne(t,"condition","whereAsync","bool")).data()];case 1:return n=i.sent(),r=pa(e.shape,n),t!==e&&e.dispose(),[2,r]}})})};var Uu=Ce({elu_:function(t){var e=Ne(t,"x","elu");return Ut.engine.runKernel(function(t,n){return n(t.elu(e))},{$x:e},function(t,e){var n=e[0];return{$x:function(){return Ut.engine.runKernel(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),Wu=Ce({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=Ne(t,"x","leakyRelu");return wu(De(e).mul(n),n)}}),Vu=Ce({prelu_:function(t,e){var n=Ne(t,"x","prelu"),r=Ne(e,"alpha","prelu");return Ut.engine.runKernel(function(t){return t.prelu(n,r)},{$x:n,$alpha:r},function(t){var e=n.greater(0);return{$x:function(){return Pu(e,t,t.mul(r))},$alpha:function(){var i=Pu(e,qe(t),t.mul(n)),o=un(r.shape,t.shape);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),ju=Ce({relu_:function(t){var e=Ne(t,"x","relu");return"bool"===e.dtype?e.toInt():Ut.engine.runKernel(function(t){return t.relu(e)},{$x:e},function(t){var n=e.step();return{$x:function(){return t.mulStrict(n.toFloat())}}})}}),qu=Ce({selu_:function(t){var e=Ne(t,"x","selu");return Ut.engine.runKernel(function(t){return t.selu(e)},{$x:e},function(t){return{$x:function(){var n=e.greater(De(0)),r=De(io),i=De(oo),o=t.mul(i),a=t.mul(r).mul(e.toFloat().exp());return Pu(n,o,a)}}})}});var Gu=Ce({transpose_:function(t,e){var n=Ne(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){d(t>=0&&t<n.rank,function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e})}),n.rank<=1?n.clone():Ut.engine.runKernel(function(t){return t.transpose(n,e)},{$x:n},function(t){var n=se(e);return{$x:function(){return t.transpose(n)}}})}});var Hu=Ce({localResponseNormalization_:function(t,e,n,r,i){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===i&&(i=.5);var o=Ne(t,"x","localResponseNormalization");d(4===o.rank||3===o.rank,function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank "+o.rank+"."}),d(w(e),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."});var a=o,s=!1;3===o.rank&&(s=!0,a=o.as4D(1,o.shape[0],o.shape[1],o.shape[2]));var u=Ut.engine.runKernel(function(t,o){return o(t.localResponseNormalization4D(a,e,n,r,i))},{x4D:a},function(t,o){var s=o[0];return{x4D:function(){return Ut.engine.runKernel(function(o){return o.LRNGrad(t,a,s,e,n,r,i)},{})}}});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}});var Ku=Ce({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var i=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(De(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=Ne(t,"x","norm"),e,n),o=i.shape;if(r){var a=I(n,t.shape);o=ie(i.shape,a)}return i.reshape(o)}});function $u(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function Xu(t){for(var e=[],n=0;n<t.length;++n)for(var r=0;r<t[n].length;++r)e.push(t[n][r]);return e}var Yu=Ce({gather_:function(t,e,n){void 0===n&&(n=0);var r=Ne(t,"x","gather"),i=Ne(e,"indices","gather","int32");n=I(n,r.shape)[0];var o=function(t,e,n){for(var r=t.shape[n],i=[],o=1,a=1,s=0;s<n;s++)i.push(t.shape[s]),o*=t.shape[s];for(s=0;s<e.rank;s++)i.push(e.shape[s]);for(s=n+1;s<t.rank;s++)i.push(t.shape[s]),a*=t.shape[s];return{batchSize:o,sliceSize:a,dimSize:r,outputShape:i}}(r,i,n);return Ut.engine.runKernel(function(t){return t.gather(r,i.flatten(),n)},{$x:r},function(t){return{$x:function(){var e=r.shape,o=i.size,a=e.slice(0,n),s=a.length,u=e.slice(n,e.length).slice(1),l=u.length,c=$u(0,s),p=$u(s+1,s+1+l),h=Xu([a,[o],u]),f=t.reshape(h),d=i.reshape([o]),m=Xu([[s],c,p]),g=f.transpose(m),y=Ju(g,d,r.shape[n]),v=se(m);return y.transpose(v)}}}).reshape(o.outputShape)}}),Ju=Ce({unsortedSegmentSum_:function(t,e,n){var r=Ne(t,"x","unsortedSegmentSum"),i=Ne(e,"segmentIds","unsortedSegmentSum","int32");return d(w(n),function(){return"numSegments must be of dtype int"}),Ut.engine.runKernel(function(t){return t.unsortedSegmentSum(r,i,n)},{$x:r},function(t){return{$x:function(){return function(t,e){for(var n=wu(e,qe(e)),r=Yu(t,n),i=iu(e,De(0,"int32")),o=r.rank-i.rank,a=0;a<o;++a)i=Go(i,a+1);i=Mu(i,Pe(r.shape,"bool"));var s=qe(r);return Pu(i,r,s)}(t,i)}}})}});var Zu=Ce({basicLSTMCell_:function(t,e,n,r,i,o){var a=Ne(t,"forgetBias","basicLSTMCell"),s=Ne(e,"lstmKernel","basicLSTMCell"),u=Ne(n,"lstmBias","basicLSTMCell"),l=Ne(r,"data","basicLSTMCell"),c=Ne(i,"c","basicLSTMCell"),p=Ne(o,"h","basicLSTMCell"),h=l.concat(p,1).matMul(s).add(u),f=h.shape[0],d=h.shape[1]/4,m=[f,d],g=h.slice([0,0],m),y=h.slice([0,d],m),v=h.slice([0,2*d],m),b=h.slice([0,3*d],m),w=g.sigmoid().mulStrict(y.tanh()).addStrict(c.mulStrict(a.add(v).sigmoid()));return[w,w.tanh().mulStrict(b.sigmoid())]}}),Qu=Ce({multiRNNCell_:function(t,e,n,r){for(var i=Ne(e,"data","multiRNNCell"),o=Se(n,"c","multiRNNCell"),a=Se(r,"h","multiRNNCell"),s=i,u=[],l=0;l<t.length;l++){var c=t[l](s,o[l],a[l]);u.push(c[0]),u.push(c[1]),s=c[1]}var p=[],h=[];for(l=0;l<u.length;l+=2)p.push(u[l]),h.push(u[l+1]);return[p,h]}});var tl=Ce({movingAverage_:function(t,e,n,r,i){void 0===i&&(i=!0);var o=Ne(t,"v","movingAverage"),a=Ne(e,"x","movingAverage"),s=Ne(n,"decay","movingAverage");(function(t,e){d(t.dtype===e.dtype,function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"})})(o,a),d(b(o.shape,a.shape),function(){return"Shape mismatch in v and x"});var u=De(1),l=u.sub(s),c=a.sub(o).mul(l);if(i){d(null!=r,function(){return"When using zeroDebias: true, step is required."});var p=Ne(r,"step","movingAverage");c=c.div(u.sub(Au(s,p)))}return o.add(c)}});var el=Ce({stridedSlice_:function(t,e,n,r,i,o,a,s,u){if(void 0===i&&(i=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===s&&(s=0),void 0===u&&(u=0),0!==a)throw new Error("ellipsis mask is not yet supported");if(0!==s)throw new Error("new axis mask is not yet supported");var l=Ne(t,"x","stridedSlice");if(r.every(function(t){return 1===t})){var c=me(l.shape,e,n,r,i,o,a,s,u),p=c[0],h=c[1],f=c[2],d=h.filter(function(t,e){return-1===f.indexOf(e)});return Ps(l,p,h).reshape(d)}return Ut.engine.runKernel(function(t){return t.stridedSlice(l,e,n,r,i,o,a,s,u)},{$x:l})}});var nl=Ce({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=Ne(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var i=r.shape[r.shape.length-1];if(e>i)throw new Error("'k' passed to topk() must be <= the last dimension ("+i+") but got "+e);var o=Ut.engine.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:o[0],indices:o[1]}}});var rl=Ce({scatterND_:function(t,e,n){var r=Ne(t,"indices","scatterND","int32"),i=Ne(e,"updates","scatterND");return fe(i,r,n),Ut.engine.runKernel(function(t){return t.scatterND(r,i,n)},{$indices:r,$updates:i})}});var il=Ce({fft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Ut.engine.runKernel(function(t){return t.fft(r)},{input:t}).reshape(t.shape)}}),ol=Ce({ifft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Ut.engine.runKernel(function(t){return t.ifft(r)},{input:t}).reshape(t.shape)}}),al=Ce({rfft_:function(t){d("float32"===t.dtype,function(){return"The dtype for rfft() must be real value but got "+t.dtype});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.zerosLike(),i=ke(t,r).as2D(n,e),o=il(i),a=Math.floor(e/2)+1,s=Ae(o),u=Te(o),l=s.split([a,e-a],s.shape.length-1),c=u.split([a,e-a],u.shape.length-1),p=t.shape.slice();return p[t.shape.length-1]=a,ke(l[0],c[0]).reshape(p)}}),sl=Ce({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),i=ol(r);return Ae(i)}var o=[n,2*(e-1)],a=Ae(t).as2D(n,e),s=Te(t).as2D(n,e),u=a.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(De(-1)),c=a.concat(u,1),p=s.concat(l,1);return r=ke(c,p).as2D(o[0],o[1]),i=ol(r),Ae(i)}}),ul=Object.freeze({fft:il,ifft:ol,rfft:al,irfft:sl});var ll=Ce({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var i=Ne(t,"sparseIndices","sparseToDense","int32"),o=Ne(e,"sparseValues","sparseToDense"),a=Ne(r,"defaultValue","sparseToDense",o.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var i=t.rank>0?t.shape[0]:1,o=t.rank>1?t.shape[1]:1;if(n.length!==o)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+o+".");var a=e.size;if(0!==e.rank&&(1!==e.rank||a!==i))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+i+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(i,o,n,a),Ut.engine.runKernel(function(t){return t.sparseToDense(i,o,n,a)},{$sparseIndices:i,$sparseValues:o,$defaultValue:a})}});var cl=Ce({gatherND_:function(t,e){var n=Ne(e,"indices","gatherND","int32"),r=Ne(t,"x","gatherND");return Ut.engine.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}});!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(t.Reduction||(t.Reduction={}));var pl=Ce({absoluteDifference_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ne(e,"labels","absoluteDifference"),a=Ne(n,"predictions","absoluteDifference"),s=null;null!=r&&(s=Ne(r,"weights","absoluteDifference")),m(o.shape,a.shape,"Error in absoluteDifference: ");var u=o.sub(a).abs();return hl(u,s,i)}}),hl=Ce({computeWeightedLoss_:function(e,n,r){void 0===r&&(r=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=Ne(e,"losses","computeWeightedLoss"),o=null;null!=n&&(o=Ne(n,"weights","computeWeightedLoss"));var a=null==o?i:i.mul(o);if(r===t.Reduction.NONE)return a;if(r===t.Reduction.SUM)return a.sum();if(r===t.Reduction.MEAN){if(null==o)return a.mean();var s=i.size/o.size,u=a.sum().div(o.sum());return s>1?u.div(De(s)):u}if(r===t.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(De(i.size));var l=o.mul(Pe(i.shape)).notEqual(De(0)).sum().toFloat();return a.sum().div(l)}throw Error("Unknown reduction: "+r)}}),fl=Ce({cosineDistance_:function(e,n,r,i,o){void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ne(e,"labels","cosineDistance"),s=Ne(n,"predictions","cosineDistance"),u=null;null!=i&&(u=Ne(i,"weights","cosineDistance")),m(a.shape,s.shape,"Error in cosineDistance: ");var l=De(1).sub(a.mul(s).sum(r,!0));return hl(l,u,o)}}),dl=Ce({hingeLoss_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ne(e,"labels","hingeLoss"),a=Ne(n,"predictions","hingeLoss"),s=null;null!=r&&(s=Ne(r,"weights","hingeLoss")),m(o.shape,a.shape,"Error in hingeLoss: ");var u=De(1);o=De(2).mul(o).sub(u);var l=u.sub(o.mul(a)).relu();return hl(l,s,i)}}),ml=Ce({huberLoss_:function(e,n,r,i,o){void 0===i&&(i=1),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ne(e,"labels","huberLoss"),s=Ne(n,"predictions","huberLoss"),u=null;null!=r&&(u=Ne(r,"weights","huberLoss")),m(a.shape,s.shape,"Error in huberLoss: ");var l=De(i),c=s.sub(a).abs(),p=Nu(c,l),h=c.sub(p),f=De(.5).mul(p.square()).add(l.mul(h));return hl(f,u,o)}}),gl=Ce({logLoss_:function(e,n,r,i,o){void 0===i&&(i=1e-7),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ne(e,"labels","logLoss"),s=Ne(n,"predictions","logLoss"),u=null;null!=r&&(u=Ne(r,"weights","logLoss")),m(a.shape,s.shape,"Error in logLoss: ");var l=De(1),c=De(i),p=a.mul(s.add(c).log()).neg().sub(l.sub(a).mul(l.sub(s).add(c).log()));return hl(p,u,o)}}),yl=Ce({meanSquaredError_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ne(e,"labels","meanSquaredError"),a=Ne(n,"predictions","meanSquaredError"),s=null;null!=r&&(s=Ne(r,"weights","meanSquaredError")),m(o.shape,a.shape,"Error in meanSquaredError: ");var u=o.squaredDifference(a);return hl(u,s,i)}}),vl=Ce({sigmoidCrossEntropy_:function(e,n,r,i,o){void 0===i&&(i=0),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ne(e,"multiClassLabels","sigmoidCrossEntropy"),s=Ne(n,"logits","sigmoidCrossEntropy"),u=null;if(null!=r&&(u=Ne(r,"weights","sigmoidCrossEntropy")),m(a.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=De(i),c=De(1),p=De(.5);a=a.mul(c.sub(l)).add(p.mul(l))}var h=function(t,e){var n=Ne(t,"labels","sigmoidCrossEntropyWithLogits"),r=Ne(e,"logits","sigmoidCrossEntropyWithLogits");m(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var i=r.relu(),o=r.mul(n),a=r.abs().neg().exp().log1p();return i.sub(o).add(a)}(a,s);return hl(h,u,o)}}),bl=Ce({softmaxCrossEntropy_:function(e,n,r,i,o){void 0===i&&(i=0),void 0===o&&(o=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ne(e,"onehotLabels","softmaxCrossEntropy"),s=Ne(n,"logits","softmaxCrossEntropy"),u=null;if(null!=r&&(u=Ne(r,"weights","softmaxCrossEntropy")),m(a.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=De(i),c=De(1),p=De(a.shape[1]);a=a.mul(c.sub(l)).add(l.div(p))}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return jt(function(t,e){var r=e.logSumExp([n],!0),i=e.toFloat().sub(r);return{value:i.mul(t).neg().sum([n]),gradFunc:function(e){var r=ie(e.shape,[n]);return[e.reshape(r).mul(t.toFloat().sub(i.exp())),e.reshape(r).mul(i.exp().sub(t.toFloat()))]}}})(t,e)}(a,s);return hl(h,u,o)}}),wl=Object.freeze({get Reduction(){return t.Reduction},absoluteDifference:pl,computeWeightedLoss:hl,cosineDistance:fl,hingeLoss:dl,huberLoss:ml,logLoss:gl,meanSquaredError:yl,sigmoidCrossEntropy:vl,softmaxCrossEntropy:bl});function xl(t,e){return void 0===e&&(e=!1),Ut.engine.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],i=Ho(n),o=t.clone(),a=_e([[1]],[1,1]),s=a.clone(),u=n>=r?r:n,l=function(t){var e,u=o,l=s,c=i;e=Ut.engine.tidy(function(){var e=o.slice([t,t],[n-t,1]),u=e.norm(),l=o.slice([t,t],[1,1]),c=l.sign().neg(),p=l.sub(c.mul(u)),h=e.div(p);s=1===h.shape[0]?a.clone():a.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var f=c.matMul(p).div(u).neg(),d=o.slice([t,0],[n-t,r]),m=f.mul(s);o=0===t?d.sub(m.matMul(s.transpose().matMul(d))):o.slice([0,0],[t,r]).concat(d.sub(m.matMul(s.transpose().matMul(d))),0);var g=i.slice([0,t],[n,i.shape[1]-t]);return i=0===t?g.sub(g.matMul(s).matMul(m.transpose())):i.slice([0,0],[n,t]).concat(g.sub(g.matMul(s).matMul(m.transpose())),1),[s,o,i]}),s=e[0],o=e[1],i=e[2],Kt([u,l,c])},c=0;c<u;++c)l(c);return!e&&n>r&&(i=i.slice([0,0],[n,r]),o=o.slice([0,0],[r,r])),[i,o]})}var Nl=Ce({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,d(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],r=function(e){d(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},i=1;i<t.length;++i)r(i)}else e=!0,t=ko(t,t.shape[0],0).map(function(t){return oa(t,[0])});d(t.length<=t[0].shape[0],function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."});var o=[],a=t,s=function(t){o.push(Ut.engine.tidy(function(){var e=a[t];if(t>0)for(var n=0;n<t;++n){var r=Qs(o[n].mulStrict(e)).mul(o[n]);e=e.sub(r)}return e.div(Ku(e,"euclidean"))}))};for(i=0;i<t.length;++i)s(i);return e?aa(o,0):o}}),Sl=Ce({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return xl(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=[],i=[];return la(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var n=xl(t,e),o=n[0],a=n[1];r.push(o),i.push(a)}),[aa(r,0).reshape(t.shape),aa(i,0).reshape(t.shape)]}}),Cl=Object.freeze({gramSchmidt:Nl,qr:Sl});function El(t,e,n,r,i){null==r&&(r=.5),null==i&&(i=Number.NEGATIVE_INFINITY);var o=t.shape[0];return n=Math.min(n,o),d(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),d(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),d(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),d(1===e.rank,function(){return"scores must be a 1D tensor"}),d(e.shape[0]===o,function(){return"scores has incompatible shape with boxes. Expected "+o+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i}}var Il=Ce({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=Ne(t,"images","resizeBilinear");d(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Ut.engine.runKernel(function(t,e){return t.resizeBilinear(i,a,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return Ut.engine.runKernel(function(e){return e.resizeBilinearBackprop(t,i,n)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),kl=Ce({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=Ne(t,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),d("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var i=r,o=!1;3===r.rank&&(o=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=Ut.engine.runKernel(function(t,e){return t.resizeNearestNeighbor(i,a,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return Ut.engine.runKernel(function(e){return e.resizeNearestNeighborBackprop(t,i,n)},{})}}});return o?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Al=Ce({nonMaxSuppression_:function(t,e,n,r,i){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY);var o=Ne(t,"boxes","nonMaxSuppression"),a=Ne(e,"scores","nonMaxSuppression"),s=El(o,a,n,r,i);return n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,Ut.engine.runKernel(function(t){return t.nonMaxSuppression(o,a,n,r,i)},{$boxes:o})}}),Tl=function(t,e,n,r,a){return void 0===r&&(r=.5),void 0===a&&(a=Number.NEGATIVE_INFINITY),i(this,void 0,void 0,function(){var i,s,u,l,c,p;return o(this,function(o){switch(o.label){case 0:return i=Ne(t,"boxes","nonMaxSuppressionAsync"),s=Ne(e,"scores","nonMaxSuppressionAsync"),u=El(i,s,n,r,a),n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,[4,i.data()];case 1:return l=o.sent(),[4,s.data()];case 2:return c=o.sent(),p=Qe(l,c,n,r,a),i!==t&&i.dispose(),s!==e&&s.dispose(),[2,p]}})})},Rl=Ce({cropAndResize_:function(t,e,n,r,i,o){var a=Ne(t,"image","cropAndResize","float32"),s=Ne(e,"boxes","cropAndResize","float32"),u=Ne(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;var l=s.shape[0];return d(4===a.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."}),d(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),d(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),d(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),d(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),d("bilinear"===i||"nearest"===i,function(){return"method must be bilinear or nearest, but was "+i}),Ut.engine.runKernel(function(t,e){return t.cropAndResize(a,s,u,r,i,o)},{$image:a,$boxes:s})}}),Dl=Object.freeze({resizeBilinear:Il,resizeNearestNeighbor:kl,nonMaxSuppression:Al,nonMaxSuppressionAsync:Tl,cropAndResize:Rl});var Ol=Ce({matMul_:function(t,e,n,r,i,o){var a;void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o="linear");var s=Ne(t,"a","fused matMul"),u=Ne(e,"b","fused matMul");a=wt(s,u),s=a[0],u=a[1];var l=n?s.shape[s.rank-2]:s.shape[s.rank-1],c=r?u.shape[u.rank-1]:u.shape[u.rank-2],p=n?s.shape[s.rank-1]:s.shape[s.rank-2],h=r?u.shape[u.rank-2]:u.shape[u.rank-1],f=s.shape.slice(0,-2),m=u.shape.slice(0,-2),g=v(f),y=v(m);d(s.rank>=2&&u.rank>=2&&s.rank===u.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+s.rank+" and "+u.rank+"."}),d(b(f,m),function(){return"Error in fused matMul: outer dimensions ("+f+") and ("+m+") of Tensors with shapes "+s.shape+" and "+u.shape+" must match."}),d(l===c,function(){return"Error in fused matMul: inner shapes ("+l+") and ("+c+") of Tensors with shapes "+s.shape+" and "+u.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var w,x=s.shape.slice(0,-2).concat([p,h]),N=n?s.as3D(g,l,p):s.as3D(g,p,l),S=r?u.as3D(y,h,c):u.as3D(y,c,h);null!=i&&ln(x,(w=wt(w=Ne(i,"bias","fused matMul"),s)[0]).shape);var C={$a:N,$b:S};return null!=i&&(C.$bias=w),Ut.engine.runKernel(function(t,e){return e(t.fusedBatchMatMul(N,S,n,r,w,o))},C,function(t,e){var a,s=e[0];if(null==o||"linear"===o)a=t;else{if("relu"!==o)throw new Error("Gradient for activation "+o+" has not been implemented yet.");a=t.mul(s.step())}var u={};return null!=i&&(u={$bias:function(){var t=a,e=un(w.shape,a.shape);return e.length>0&&(t=t.sum(e)),t.reshape(w.shape)}}),n||r?!n&&r?Object.assign({$a:function(){return a.matMul(S,!1,!1)},$b:function(){return a.matMul(N,!0,!1)}},u):n&&!r?Object.assign({$a:function(){return S.matMul(a,!1,!0)},$b:function(){return N.matMul(a,!1,!1)}},u):Object.assign({$a:function(){return S.matMul(a,!0,!0)},$b:function(){return a.matMul(N,!0,!0)}},u):Object.assign({$a:function(){return a.matMul(S,!1,!0)},$b:function(){return N.matMul(a,!0,!1)}},u)}).reshape(x)}}),_l=Object.freeze({matMul:Ol}),Ml=Object.freeze({image:Dl,linalg:Cl,losses:wl,spectral:ul,fused:_l,op:Ce,batchNormalization2d:Za,batchNormalization3d:Qa,batchNormalization4d:ts,batchNormalization:es,batchNorm:ns,batchNorm2d:rs,batchNorm3d:is,batchNorm4d:os,complex:ke,real:Ae,imag:Te,concat:No,concat1d:So,concat2d:Co,concat3d:Eo,concat4d:Io,split:ko,conv1d:vs,conv2d:bs,conv3d:ws,conv2dDerFilter:xs,depthwiseConv2d:Ns,separableConv2d:Ss,conv2dTranspose:Cs,matMul:Es,dot:Is,outerProduct:ks,reverse:As,reverse1d:Ts,reverse2d:Rs,reverse3d:Ds,reverse4d:Os,maxPool:Ls,avgPool:Fs,pool:zs,slice:Ps,slice1d:Bs,slice2d:Us,slice3d:Ws,slice4d:Vs,abs:da,acos:ma,acosh:ga,asin:ya,asinh:va,atan:ba,atanh:wa,ceil:xa,clipByValue:Na,cos:Sa,cosh:Ca,erf:Ea,exp:Ia,expm1:ka,floor:Aa,log:Ta,log1p:Ra,logSigmoid:Da,neg:Oa,reciprocal:_a,round:Ma,rsqrt:La,sigmoid:Fa,sign:za,sin:Pa,sinh:Ba,softplus:Ua,sqrt:Wa,square:Va,step:ja,tan:qa,tanh:Ga,all:qs,any:Gs,argMax:Hs,argMin:Ks,logSumExp:$s,max:Xs,mean:Ys,min:Js,moments:Zs,sum:Qs,prod:tu,equal:eu,equalStrict:nu,greater:ru,greaterEqual:iu,greaterEqualStrict:ou,greaterStrict:au,less:su,lessEqual:uu,lessEqualStrict:lu,lessStrict:cu,notEqual:pu,notEqualStrict:hu,add:fu,addN:du,addStrict:mu,atan2:gu,div:yu,divStrict:vu,floorDiv:bu,maximum:wu,maximumStrict:xu,minimum:Nu,minimumStrict:Su,mod:Cu,modStrict:Eu,mul:Iu,mulStrict:ku,pow:Au,powStrict:Tu,squaredDifference:Ru,squaredDifferenceStrict:Du,sub:Ou,subStrict:_u,elu:Uu,leakyRelu:Wu,prelu:Vu,relu:ju,selu:qu,logicalAnd:Mu,logicalNot:Lu,logicalOr:Fu,logicalXor:zu,where:Pu,whereAsync:Bu,buffer:Po,print:Bo,batchToSpaceND:Uo,cast:Wo,clone:Vo,cumsum:jo,depthToSpace:qo,expandDims:Go,eye:Ho,multinomial:Ko,oneHot:$o,pad:Xo,pad1d:Yo,pad2d:Jo,pad3d:Zo,pad4d:Qo,rand:ta,randomNormal:ea,randomUniform:na,reshape:ra,spaceToBatchND:ia,squeeze:oa,stack:aa,tile:sa,truncatedNormal:ua,unstack:la,setdiff1dAsync:ca,fill:Ue,linspace:We,ones:Pe,range:Ve,scalar:De,tensor:Re,tensor1d:Oe,tensor2d:_e,tensor3d:Me,tensor4d:Le,tensor5d:Fe,tensor6d:ze,zeros:Be,onesLike:je,zerosLike:qe,transpose:Gu,softmax:Ee,logSoftmax:Ie,localResponseNormalization:Hu,norm:Ku,gather:Yu,unsortedSegmentSum:Ju,basicLSTMCell:Zu,multiRNNCell:Qu,movingAverage:tl,stridedSlice:el,topk:nl,scatterND:rl,fft:il,ifft:ol,rfft:al,irfft:sl,sparseToDense:ll,gatherND:cl});var Ll=function(){function t(){this.blockSize=48,this.firstUse=!0,Ut.get("IS_BROWSER")&&(this.fromPixels2DContext=document.createElement("canvas").getContext("2d"))}return t.prototype.setDataMover=function(t){this.data=new Ge(t)},t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,Ut.get("IS_NODE")&&Yt("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(t))throw new Error("Data buffer is already registered");this.data.set(t,{dtype:n})},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n,r;if(Ut.get("IS_NODE")&&null==t.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=t.getContext)n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;else if(t instanceof ImageData)n=t.data;else{if(!(t instanceof HTMLImageElement||t instanceof HTMLVideoElement))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+t.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),n=this.fromPixels2DContext.getImageData(0,0,t.width,t.height).data}if(4===e)r=new Int32Array(n);else{var i=t.width*t.height;r=new Int32Array(i*e);for(var o=0;o<i;o++)for(var a=0;a<e;++a)r[o*e+a]=n[4*o+a]}return Me(r,[t.height,t.width,e],"int32")},t.prototype.read=function(t){return i(this,void 0,void 0,function(){return o(this,function(e){return[2,this.readSync(t)]})})},t.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?Xe(r.real.dataSync(),r.imag.dataSync()):this.data.get(t).values},t.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},t.prototype.time=function(t){return i(this,void 0,void 0,function(){var e;return o(this,function(n){return e=K(),t(),[2,{kernelMs:K()-e}]})})},t.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},t.prototype.complex=function(t,e){var n=lt.make(t.shape,{},"complex64");return this.data.get(n.dataId).complexTensors={real:Ut.engine.keep(t.clone()),imag:Ut.engine.keep(e.clone())},n},t.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},t.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},t.prototype.assertNotComplex=function(t,e){Array.isArray(t)||(t=[t]),t.forEach(function(t){null!=t&&d("complex64"!==t.dtype,function(){return e+" does not support complex64 tensors."})})},t.prototype.slice=function(t,e,n){if(this.assertNotComplex(t,"slice"),ve(t.shape,e,n)){var r=be(e,t.strides),i=v(n);return Re(t.dataSync().subarray(r,r+i),n,t.dtype)}for(var o=Po(n,t.dtype),a=t.bufferSync(),s=0;s<o.size;++s){var u=o.indexToLoc(s).map(function(t,n){return t+e[n]});o.values[s]=a.get.apply(a,u)}return o.toTensor()},t.prototype.stridedSlice=function(t,e,n,r,i,o,a,s,u){this.assertNotComplex(t,"stridedSlice");var l=me(t.shape,e,n,r,i,o,a,s,u),c=l[0],p=l[1],h=l[2],f=p.filter(function(t,e){return-1===h.indexOf(e)});if(f.some(function(t){return 0===t}))return Re([],f);for(var d=Po(p,t.dtype),m=t.bufferSync(),g=0;g<d.size;g++){for(var y=d.indexToLoc(g),v=new Array(y.length),b=0;b<v.length;b++)v[b]=y[b]*r[b]+c[b];d.set.apply(d,[m.get.apply(m,v)].concat(y))}return d.toTensor().reshape(f)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,o=0;o<t.rank;o++)o!==e&&(r[i++]=t.shape[o]);var a=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(o=0;o<u.length;o++)a[e]=o,u[o]=this.slice(t,a,s).reshape(r);return u},t.prototype.reverse=function(t,e){this.assertNotComplex(t,"reverse");for(var n=Po(t.shape,t.dtype),r=t.bufferSync(),i=function(i){var o=n.indexToLoc(i),a=o.slice();e.forEach(function(e){return a[e]=t.shape[e]-1-a[e]}),n.set.apply(n,[r.get.apply(r,a)].concat(o))},o=0;o<n.size;o++)i(o);return n.toTensor()},t.prototype.concat=function(t,e){this.assertNotComplex(t,"concat");var n=t.map(function(t){var n=v(t.shape.slice(e));return t.as2D(-1,n)}),r=le(n.map(function(t){return t.shape}),1),i=Po(r,t[0].dtype).values;if(1===n[0].shape[0]){var o=0;n.forEach(function(t){i.set(t.dataSync(),o),o+=t.size})}else{var a=0;n.forEach(function(t){for(var e=t.dataSync(),n=0,o=0;o<t.shape[0];++o)for(var s=o*r[1]+a,u=0;u<t.shape[1];++u)i[s+u]=e[n++];a+=t.shape[1]})}var s=le(t.map(function(t){return t.shape}),e);return Re(i,s,t[0].dtype)},t.prototype.neg=function(t){return this.assertNotComplex(t,"neg"),this.multiply(De(-1),t)},t.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t+n,imag:e+r}}):this.broadcastedBinaryOp(t,e,vt(t.dtype,e.dtype),function(t,e){return t+e})},t.prototype.addN=function(t){this.assertNotComplex(t,"addN");for(var e=t.map(function(t){return t.dataSync()}),n=Po(t[0].shape,t[0].dtype),r=n.values,i=0;i<t.length;i++)for(var o=e[i],a=0;a<r.length;a++)r[a]+=o[a];return n.toTensor()},t.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t-n,imag:e-r}}):this.broadcastedBinaryOp(t,e,vt(t.dtype,e.dtype),function(t,e){return t-e})},t.prototype.pow=function(t,e){return this.assertNotComplex([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.pow(t,e)})},t.prototype.batchMatMul=function(t,e,n,r){this.assertNotComplex([t,e],"matMul");for(var i=n?t.shape[1]:t.shape[2],o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],s=t.shape[0],u=t.dataSync(),l=e.dataSync(),c=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],p=c[0],h=c[1],f=c[2],d=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],m=d[0],g=d[1],y=d[2],v=o*a,b=Po([s,o,a],t.dtype),w=b.values,x=this.blockSize,N=0;N<s;N++)for(var S=0;S<o;S+=x)for(var C=0;C<a;C+=x)for(var E=0;E<i;E+=x)for(var I=Math.min(S+x,o),k=Math.min(C+x,a),A=Math.min(E+x,i),T=S;T<I;T++)for(var R=C;R<k;R++){for(var D=0,O=E;O<A;O++)D+=u[N*p+T*h+O*f]*l[O*m+R*g+N*y];w[N*v+(T*a+R)]+=D}return b.toTensor()},t.prototype.fusedBatchMatMul=function(t,e,n,r,i,o){var a=this.batchMatMul(t,e,n,r);return i&&(a=this.add(a,i)),o&&(a=function(t,e,n){if("linear"===e)return t.linear(n);if("relu"===e)return t.relu(n);throw new Error("Activation "+e+" has not been implemented for the CPU backend.")}(this,o,a)),a},t.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n}}):this.broadcastedBinaryOp(t,e,vt(t.dtype,e.dtype),function(t,e){return t*e})},t.prototype.realDivide=function(t,e){return this.assertNotComplex([t,e],"realDivide"),this.broadcastedBinaryOp(t,e,"float32",function(t,e){return t/e})},t.prototype.floorDiv=function(t,e){return this.assertNotComplex([t,e],"floorDiv"),this.broadcastedBinaryOp(t,e,"int32",function(t,e){return Math.floor(t/e)})},t.prototype.sum=function(t,e){this.assertNotComplex(t,"sum"),oe("sum",e,t.rank);for(var n=re(t.shape,e),r=n[0],i=n[1],o=Be(r,vt(t.dtype,"int32")),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;l<s.length;++l){for(var c=l*a,p=0,h=0;h<a;++h)p+=u[c+h];s[l]=p}return o},t.prototype.prod=function(t,e){this.assertNotComplex(t,"sum");for(var n=re(t.shape,e),r=n[0],i=n[1],o=Be(r,vt(t.dtype,"int32")),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;l<s.length;++l){for(var c=l*a,p=1,h=0;h<a;++h)p*=u[c+h];s[l]=p}return o},t.prototype.unsortedSegmentSum=function(t,e,n){this.assertNotComplex(t,"unsortedSegmentSum");for(var r=[],i=t.rank-e.rank,o=0;o<i;++o)e=e.expandDims(o+1);for(o=0;o<n;++o){var a=De(o,"int32"),s=eu(a,e).asType("float32").mul(t).sum(0);r.push(s)}return aa(r)},t.prototype.argMin=function(t,e){this.assertNotComplex(t,"argMin");var n=[e];oe("argMin",n,t.rank);for(var r=re(t.shape,n),i=r[0],o=r[1],a=Be(i,"int32"),s=v(o),u=a.dataSync(),l=t.dataSync(),c=0;c<u.length;++c){for(var p=c*s,h=l[p],f=0,d=0;d<s;++d){var m=l[p+d];m<h&&(h=m,f=d)}u[c]=f}return a},t.prototype.argMax=function(t,e){this.assertNotComplex(t,"argMax");var n=[e];oe("argMax",n,t.rank);for(var r=re(t.shape,n),i=r[0],o=r[1],a=Be(i,"int32"),s=v(o),u=a.dataSync(),l=t.dataSync(),c=0;c<u.length;++c){for(var p=c*s,h=l[p],f=0,d=0;d<s;++d){var m=l[p+d];m>h&&(h=m,f=d)}u[c]=f}return a},t.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var i=vt(t.dtype,"int32"),o=Be(t.shape,i),a=o.dataSync(),s=t.dataSync(),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;c<s.length;c+=u)for(var p=0;p<u;p++){var h=l(c,p);if(0===p)a[h]=n?0:s[h];else{var f=l(c,p-1);a[h]=n?s[f]+a[f]:s[h]+a[f]}}return o},t.prototype.equal=function(t,e){return this.assertNotComplex([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t===e?1:0})},t.prototype.notEqual=function(t,e){return this.assertNotComplex([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t!==e?1:0})},t.prototype.less=function(t,e){return this.assertNotComplex([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<e?1:0})},t.prototype.lessEqual=function(t,e){return this.assertNotComplex([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<=e?1:0})},t.prototype.greater=function(t,e){return this.assertNotComplex([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>e?1:0})},t.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},t.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=t.dataSync(),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return lt.make(t.shape,{values:n},"bool")},t.prototype.logicalAnd=function(t,e){return this.assertNotComplex([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t&&e})},t.prototype.logicalOr=function(t,e){return this.assertNotComplex([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t||e})},t.prototype.select=function(t,e,n){this.assertNotComplex([t,e,n],"select");for(var r=t.dataSync(),i=e.dataSync(),o=n.dataSync(),a=Be(e.shape,vt(e.dtype,n.dtype)),s=a.dataSync(),u=0,l=0===t.rank||t.rank>1||1===e.rank?1:e.shape[1],c=0;c<r.length;c++)for(var p=0;p<l;p++)1===r[c]?s[u++]=i[c]:s[u++]=o[c];return a},t.prototype.where=function(t){this.assertNotComplex([t],"where");var e=t.dataSync();return pa(t.shape,e)},t.prototype.topk=function(t,e,n){return this.assertNotComplex(t,"topk"),nn(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){this.assertNotComplex(t,"min"),oe("min",e,t.rank);for(var n=re(t.shape,e),r=n[0],i=n[1],o=Be(r,t.dtype),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;l<s.length;++l){for(var c=l*a,p=u[c],h=0;h<a;++h){var f=u[c+h];f<p&&(p=f)}s[l]=p}return o},t.prototype.minimum=function(t,e){return this.assertNotComplex([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.min(t,e)})},t.prototype.mod=function(t,e){return this.assertNotComplex([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e})},t.prototype.max=function(t,e){this.assertNotComplex(t,"max"),oe("max",e,t.rank);for(var n=re(t.shape,e),r=n[0],i=n[1],o=Be(r,t.dtype),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;l<s.length;++l){for(var c=l*a,p=u[c],h=0;h<a;++h){var f=u[c+h];f>p&&(p=f)}s[l]=p}return o},t.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},t.prototype.all=function(t,e){this.assertNotComplex(t,"all"),oe("all",e,t.rank);for(var n=re(t.shape,e),r=n[0],i=n[1],o=Be(r,t.dtype),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;l<s.length;++l){for(var c=l*a,p=u[c],h=0;h<a;++h){var f=u[c+h];p=p&&f}s[l]=p}return o},t.prototype.any=function(t,e){this.assertNotComplex(t,"any"),oe("any",e,t.rank);for(var n=re(t.shape,e),r=n[0],i=n[1],o=Be(r,t.dtype),a=v(i),s=o.dataSync(),u=t.dataSync(),l=0;l<s.length;++l){for(var c=l*a,p=u[c],h=0;h<a;++h){var f=u[c+h];p=p||f}s[l]=p}return o},t.prototype.squaredDifference=function(t,e){return this.assertNotComplex([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t-e;return n*n})},t.prototype.ceil=function(t){this.assertNotComplex(t,"ceil");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return lt.make(t.shape,{values:n})},t.prototype.floor=function(t){this.assertNotComplex(t,"floor");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return lt.make(t.shape,{values:n})},t.prototype.sign=function(t){this.assertNotComplex(t,"x");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return lt.make(t.shape,{values:n})},t.prototype.round=function(t){this.assertNotComplex(t,"round");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r){var i=Math.floor(e[r]);e[r]-i<.5?n[r]=Math.floor(e[r]):e[r]-i>.5?n[r]=Math.ceil(e[r]):n[r]=i%2==0?i:i+1}return lt.make(t.shape,{values:n})},t.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return lt.make(t.shape,{values:n})},t.prototype.expm1=function(t){this.assertNotComplex(t,"expm1");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return lt.make(t.shape,{values:n})},t.prototype.log=function(t){this.assertNotComplex(t,"log");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r){var i=e[r];n[r]=Math.log(i)}return lt.make(t.shape,{values:n})},t.prototype.log1p=function(t){this.assertNotComplex(t,"log1p");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r){var i=e[r];n[r]=Math.log1p(i)}return lt.make(t.shape,{values:n})},t.prototype.sqrt=function(t){this.assertNotComplex(t,"sqrt");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r){var i=e[r];n[r]=Math.sqrt(i)}return lt.make(t.shape,{values:n})},t.prototype.rsqrt=function(t){this.assertNotComplex(t,"rsqrt");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r){var i=e[r];n[r]=1/Math.sqrt(i)}return lt.make(t.shape,{values:n})},t.prototype.square=function(t){this.assertNotComplex(t,"square");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r){var i=e[r];n[r]=i*i}return lt.make(t.shape,{values:n})},t.prototype.reciprocal=function(t){this.assertNotComplex(t,"reciprocal");for(var e=t.dataSync(),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return lt.make(t.shape,{values:n})},t.prototype.linear=function(t){return t},t.prototype.relu=function(t){this.assertNotComplex(t,"relu");for(var e=Be(t.shape,t.dtype),n=e.dataSync(),r=t.dataSync(),i=0;i<r.length;++i)n[i]=Math.max(0,r[i]);return e},t.prototype.prelu=function(t,e){return this.assertNotComplex([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return t<0?e*t:t})},t.prototype.elu=function(t){this.assertNotComplex(t,"elu");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r){var i=n[r];e[r]=i>=0?i:Math.exp(i)-1}return lt.make(t.shape,{values:e})},t.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=e.dataSync(),i=t.dataSync(),o=0;o<r.length;++o){var a=r[o];n[o]=a>=1?i[o]:i[o]*(a+1)}return lt.make(e.shape,{values:n})},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=io,n=oo,r=new Float32Array(t.size),i=t.dataSync(),o=0;o<i.length;++o){var a=i[o];r[o]=a>=0?n*a:e*(Math.exp(a)-1)}return lt.make(t.shape,{values:r})},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),i=t.dataSync(),o=0;o<i.length;++o){var a=i[o];r[o]=a>n?n:a<e?e:a}return lt.make(t.shape,{values:r})},t.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return lt.make(t.shape,{values:e})},t.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<t.size;++r){var i=n[2*r],o=n[2*r+1];e[r]=Math.hypot(i,o)}return lt.make(t.shape,{values:e})},t.prototype.int=function(t){this.assertNotComplex(t,"int");for(var e=new Int32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=n[r];return lt.make(t.shape,{values:e},"int32")},t.prototype.sigmoid=function(t){this.assertNotComplex(t,"sigmoid");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return lt.make(t.shape,{values:e})},t.prototype.softplus=function(t){this.assertNotComplex(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=t.dataSync(),i=0;i<r.length;++i){var o,a=r[i]>-e,s=r[i]<e,u=Math.exp(r[i]);o=s?u:a?r[i]:Math.log(1+u),n[i]=o}return lt.make(t.shape,{values:n})},t.prototype.sin=function(t){this.assertNotComplex(t,"sin");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return lt.make(t.shape,{values:e})},t.prototype.cos=function(t){this.assertNotComplex(t,"cos");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return lt.make(t.shape,{values:e})},t.prototype.tan=function(t){this.assertNotComplex(t,"tan");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return lt.make(t.shape,{values:e})},t.prototype.asin=function(t){this.assertNotComplex(t,"asin");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return lt.make(t.shape,{values:e})},t.prototype.acos=function(t){this.assertNotComplex(t,"acos");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return lt.make(t.shape,{values:e})},t.prototype.atan=function(t){this.assertNotComplex(t,"atan");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return lt.make(t.shape,{values:e})},t.prototype.atan2=function(t,e){return this.assertNotComplex([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.atan2(t,e)})},t.prototype.sinh=function(t){this.assertNotComplex(t,"sinh");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return lt.make(t.shape,{values:e})},t.prototype.cosh=function(t){this.assertNotComplex(t,"cosh");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return lt.make(t.shape,{values:e})},t.prototype.tanh=function(t){this.assertNotComplex(t,"tanh");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=x(n[r]);return lt.make(t.shape,{values:e})},t.prototype.asinh=function(t){this.assertNotComplex(t,"asinh");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return lt.make(t.shape,{values:e})},t.prototype.acosh=function(t){this.assertNotComplex(t,"acosh");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return lt.make(t.shape,{values:e})},t.prototype.atanh=function(t){this.assertNotComplex(t,"atanh");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return lt.make(t.shape,{values:e})},t.prototype.erf=function(t){this.assertNotComplex(t,"erf");for(var e=new Float32Array(t.size),n=t.dataSync(),r=0;r<n.length;++r){var i=n[r],o=1/(1+.3275911*i);e[r]=1-((((1.061405429*o-1.453152027)*o+1.421413741)*o-.284496736)*o+.254829592)*o*Math.exp(-i*i)}return lt.make(t.shape,{values:e})},t.prototype.step=function(t,e){void 0===e&&(e=0),this.assertNotComplex(t,"step");for(var n=new Float32Array(t.size),r=t.dataSync(),i=0;i<r.length;++i){var o=r[i];isNaN(o)?n[i]=NaN:n[i]=o>0?1:e}return lt.make(t.shape,{values:n})},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=Po(n.outShape,t.dtype),c=t.dataSync(),p=e.dataSync(),h=l.values,f=0;f<n.batchSize;++f)for(var d=f*t.strides[0],m=f*l.strides[0],g=0;g<n.outHeight;++g)for(var y=m+g*l.strides[1],v=g*n.strideHeight-s,b=0;b<r;b++){var w=v+b*o;if(!(w<0||w>=n.inHeight))for(var x=b*e.strides[0],N=d+w*t.strides[1],S=0;S<n.outWidth;++S)for(var C=y+S*n.outChannels,E=S*n.strideWidth-u,I=0;I<i;I++){var k=E+I*a;if(!(k<0||k>=n.inWidth))for(var A=x+I*e.strides[1],T=N+k*n.inChannels,R=A,D=0;D<n.inChannels;++D){for(var O=c[T+D],_=0;_<n.outChannels;++_)h[C+_]+=O*p[R+_];R+=n.outChannels}}}return l.toTensor()},t.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,i=n.filterHeight,o=n.filterWidth,a=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,l=n.padInfo.front,c=n.padInfo.left,p=n.padInfo.top,h=Po(n.outShape,t.dtype),f=t.dataSync(),d=e.dataSync(),m=h.values,g=0;g<n.batchSize;++g)for(var y=g*t.strides[0],v=g*h.strides[0],b=0;b<n.outDepth;++b)for(var w=v+b*h.strides[1],x=b*n.strideDepth-l,N=0;N<r;N++){var S=x+N*a;if(!(S<0||S>=n.inDepth))for(var C=N*e.strides[0],E=y+S*t.strides[1],I=0;I<n.outHeight;++I)for(var k=w+I*h.strides[2],A=I*n.strideHeight-p,T=0;T<i;T++){var R=A+T*s;if(!(R<0||R>=n.inHeight))for(var D=C+T*e.strides[1],O=E+R*t.strides[2],_=0;_<n.outWidth;++_)for(var M=k+_*n.outChannels,L=_*n.strideWidth-c,F=0;F<o;F++){var z=L+F*u;if(!(z<0||z>=n.inWidth))for(var P=D+F*e.strides[2],B=O+z*n.inChannels,U=P,W=0;W<n.inChannels;++W){for(var V=f[B+W],j=0;j<n.outChannels;++j)m[M+j]+=V*d[U+j];U+=n.outChannels}}}}return h.toTensor()},t.prototype.conv2dDerInput=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerInput");for(var r=Po(n.inShape,"float32"),i=r.values,o=r.strides,a=o[0],s=o[1],u=o[2],l=t.dataSync(),c=t.strides,p=c[0],h=c[1],f=c[2],d=e.dataSync(),m=e.strides,g=m[0],y=m[1],v=m[2],b=n.batchSize,w=n.filterHeight,x=n.filterWidth,N=n.inChannels,S=n.inHeight,C=n.inWidth,E=n.outChannels,I=n.outHeight,k=n.outWidth,A=n.strideHeight,T=n.strideWidth,R=w-1-n.padInfo.top,D=x-1-n.padInfo.left,O=0;O<b;++O)for(var _=0;_<N;++_)for(var M=0;M<S;++M)for(var L=M-R,F=Math.max(0,Math.ceil(L/A)),z=Math.min(I,(w+L)/A),P=0;P<C;++P){for(var B=P-D,U=Math.max(0,Math.ceil(B/T)),W=Math.min(k,(x+B)/T),V=0,j=F;j<z;++j)for(var q=j*A-L,G=U;G<W;++G)for(var H=p*O+h*j+f*G,K=g*(w-1-q)+y*(x-1-(G*T-B))+v*_,$=0;$<E;++$)V+=l[H+$]*d[K+$];i[a*O+s*M+u*P+_]=V}return r.toTensor()},t.prototype.conv3dDerInput=function(t,e,n){for(var r=Po(n.inShape,"float32"),i=r.values,o=r.strides,a=o[0],s=o[1],u=o[2],l=o[3],c=t.dataSync(),p=t.strides,h=p[0],f=p[1],d=p[2],m=p[3],g=e.dataSync(),y=e.strides,v=y[0],b=y[1],w=y[2],x=y[3],N=n.batchSize,S=n.filterDepth,C=n.filterHeight,E=n.filterWidth,I=n.inChannels,k=n.inDepth,A=n.inHeight,T=n.inWidth,R=n.outChannels,D=n.outDepth,O=n.outHeight,_=n.outWidth,M=n.strideDepth,L=n.strideHeight,F=n.strideWidth,z=S-1-n.padInfo.front,P=C-1-n.padInfo.top,B=E-1-n.padInfo.left,U=0;U<N;++U)for(var W=0;W<I;++W)for(var V=0;V<k;++V)for(var j=V-z,q=Math.max(0,Math.ceil(j/M)),G=Math.min(D,(S+j)/M),H=0;H<A;++H)for(var K=H-P,$=Math.max(0,Math.ceil(K/L)),X=Math.min(O,(C+K)/L),Y=0;Y<T;++Y){for(var J=Y-B,Z=Math.max(0,Math.ceil(J/F)),Q=Math.min(_,(E+J)/F),tt=0,et=q;et<G;++et)for(var nt=et*M-j,rt=$;rt<X;++rt)for(var it=rt*L-K,ot=Z;ot<Q;++ot)for(var at=h*U+f*et+d*rt+m*ot,st=v*(S-1-nt)+b*(C-1-it)+w*(E-1-(ot*F-J))+x*W,ut=0;ut<R;++ut)tt+=c[at+ut]*g[st+ut];i[a*U+s*V+u*H+l*Y+W]=tt}return r.toTensor()},t.prototype.conv2dDerFilter=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerFilter");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s=Po(n.filterShape,"float32"),u=n.padInfo.left,l=n.padInfo.top,c=t.bufferSync(),p=e.bufferSync(),h=0;h<o;++h)for(var f=Math.max(0,Math.ceil((l-h)/r)),d=Math.min(n.outHeight,(n.inHeight+l-h)/r),m=0;m<a;++m)for(var g=Math.max(0,Math.ceil((u-m)/i)),y=Math.min(n.outWidth,(n.inWidth+u-m)/i),v=0;v<n.inChannels;++v)for(var b=0;b<n.outChannels;++b){for(var w=0,x=0;x<n.batchSize;++x)for(var N=f;N<d;++N)for(var S=h+N*r-l,C=g;C<y;++C){var E=m+C*i-u;w+=c.get(x,S,E,v)*p.get(x,N,C,b)}s.set(w,h,m,v,b)}return s.toTensor()},t.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,i=n.strideHeight,o=n.strideWidth,a=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=Po(n.filterShape,"float32"),c=l.values,p=l.strides,h=p[0],f=p[1],d=p[2],m=p[3],g=e.dataSync(),y=e.strides,v=y[0],b=y[1],w=y[2],x=y[3],N=t.dataSync(),S=t.strides,C=S[0],E=S[1],I=S[2],k=S[3],A=n.padInfo.front,T=n.padInfo.left,R=n.padInfo.top,D=0;D<a;++D)for(var O=Math.max(0,Math.ceil((A-D)/r)),_=Math.min(n.outDepth,(n.inDepth+A-D)/r),M=D*h,L=0;L<s;++L)for(var F=Math.max(0,Math.ceil((R-L)/i)),z=Math.min(n.outHeight,(n.inHeight+R-L)/i),P=L*f+M,B=0;B<u;++B)for(var U=Math.max(0,Math.ceil((T-B)/o)),W=Math.min(n.outWidth,(n.inWidth+T-B)/o),V=B*d+P,j=0;j<n.inChannels;++j)for(var q=j*m+V,G=0;G<n.outChannels;++G){for(var H=0,K=0;K<n.batchSize;++K)for(var $=K*C,X=K*v,Y=O;Y<_;++Y)for(var J=(D+Y*r-A)*E+$,Z=Y*b+X,Q=F;Q<z;++Q)for(var tt=(L+Q*i-R)*I+J,et=Q*w+Z,nt=U;nt<W;++nt){var rt=nt*x+et;H+=N[(B+nt*o-T)*k+tt+j]*g[rt+G]}c[q+G]=H}return l.toTensor()},t.prototype.depthwiseConv2D=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2D");for(var r=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=n.outChannels/n.inChannels,c=Po(n.outShape,t.dtype),p=t.dataSync(),h=e.dataSync(),f=c.values,d=0;d<n.batchSize;++d)for(var m=d*t.strides[0],g=d*c.strides[0],y=0;y<n.outHeight;++y)for(var v=g+y*c.strides[1],b=y*n.strideHeight-s,w=0;w<r;++w){var x=b+w*o;if(!(x<0||x>=n.inHeight))for(var N=w*e.strides[0],S=m+x*t.strides[1],C=0;C<n.outWidth;++C)for(var E=v+C*c.strides[2],I=C*n.strideWidth-u,k=0;k<i;++k){var A=I+k*a;if(!(A<0||A>=n.inWidth))for(var T=N+k*e.strides[1],R=S+A*n.inChannels,D=E,O=T,_=0;_<n.inChannels;++_){for(var M=p[R+_],L=0;L<l;++L)f[D+L]+=M*h[O+L];D+=l,O+=l}}}return c.toTensor()},t.prototype.depthwiseConv2DDerInput=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerInput");for(var r=Po(n.inShape,"float32"),i=r.values,o=r.strides,a=o[0],s=o[1],u=o[2],l=t.dataSync(),c=t.strides,p=c[0],h=c[1],f=c[2],d=e.dataSync(),m=e.strides,g=m[0],y=m[1],v=m[2],b=n.batchSize,w=n.filterHeight,x=n.filterWidth,N=n.inChannels,S=n.inHeight,C=n.inWidth,E=n.outChannels,I=n.outHeight,k=n.outWidth,A=n.strideHeight,T=n.strideWidth,R=w-1-n.padInfo.top,D=x-1-n.padInfo.left,O=E/N,_=0;_<b;++_)for(var M=0;M<N;++M)for(var L=0;L<S;++L)for(var F=L-R,z=Math.max(0,Math.ceil(F/A)),P=Math.min(I,(w+F)/A),B=0;B<C;++B){for(var U=B-D,W=Math.max(0,Math.ceil(U/T)),V=Math.min(k,(x+U)/T),j=0,q=z;q<P;++q)for(var G=q*A-F,H=W;H<V;++H)for(var K=p*_+h*q+f*H,$=g*(w-1-G)+y*(x-1-(H*T-U))+v*M,X=0;X<O;++X)j+=l[K+(M*O+X)]*d[$+X];i[a*_+s*L+u*B+M]=j}return r.toTensor()},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s=Po(n.filterShape,"float32"),u=n.padInfo.left,l=n.padInfo.top,c=n.outChannels/n.inChannels,p=t.bufferSync(),h=e.bufferSync(),f=0;f<o;++f)for(var d=Math.max(0,Math.ceil((l-f)/r)),m=Math.min(n.outHeight,(n.inHeight+l-f)/r),g=0;g<a;++g)for(var y=Math.max(0,Math.ceil((u-g)/i)),v=Math.min(n.outWidth,(n.inWidth+u-g)/i),b=0;b<n.outChannels;++b){for(var w=Math.trunc(b/c),x=b%c,N=0,S=0;S<n.batchSize;++S)for(var C=d;C<m;++C)for(var E=f+C*r-l,I=y;I<v;++I){var k=g+I*i-u;N+=p.get(S,E,k,w)*h.get(S,C,I,b)}s.set(N,f,g,w,x)}return s.toTensor()},t.prototype.tile=function(t,e){this.assertNotComplex(t,"tile");for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var i=Po(n,t.dtype),o=t.bufferSync();for(r=0;r<i.values.length;++r){for(var a=i.indexToLoc(r),s=new Array(t.rank),u=0;u<s.length;u++)s[u]=a[u]%t.shape[u];var l=o.locToIndex(s);i.values[r]=o.values[l]}return i.toTensor()},t.prototype.pad=function(t,e,n){this.assertNotComplex(t,"pad");var r=e.map(function(e,n){return e[0]+t.shape[n]+e[1]}),i=e.map(function(t){return t[0]}),o=t.bufferSync(),a=Po(r,t.dtype);0!==n&&a.values.fill(n);for(var s=0;s<t.size;s++){var u=o.indexToLoc(s),l=u.map(function(t,e){return t+i[e]});a.set.apply(a,[o.get.apply(o,u)].concat(l))}return a.toTensor()},t.prototype.transpose=function(t,e){this.assertNotComplex(t,"transpose");for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[e[r]];var i=t.dataSync(),o=Po(n,t.dtype),a=t.bufferSync();for(r=0;r<t.size;++r){for(var s=a.indexToLoc(r),u=new Array(s.length),l=0;l<u.length;l++)u[l]=s[e[l]];var c=o.locToIndex(u);o.values[c]=i[r]}return o.toTensor()},t.prototype.gather=function(t,e,n){this.assertNotComplex([t,e],"gather");var r=t.shape.slice(),i=e.dataSync();r[n]=i.length;for(var o=Po(r,t.dtype),a=t.bufferSync(),s=0;s<o.size;++s){var u=o.indexToLoc(s),l=u.slice();l[n]=i[u[n]];var c=a.locToIndex(l);o.values[s]=a.values[c]}return o.toTensor()},t.prototype.batchToSpaceND=function(t,e,n){this.assertNotComplex([t],"batchToSpaceND");var r=e.reduce(function(t,e){return t*e}),i=Jt(t.shape,e,r),o=Zt(i.length,e.length),a=Qt(t.shape,e,r),s=te(n,e.length),u=ee(a,n,e.length);return t.reshape(i).transpose(o).reshape(a).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){this.assertNotComplex([t],"spaceToBatchND");var r=e.reduce(function(t,e){return t*e}),i=[[0,0]];i.push.apply(i,n);for(var o=1+e.length;o<t.shape.length;++o)i.push([0,0]);var a=t.pad(i),s=Jt(a.shape,e,r,!1),u=Zt(s.length,e.length,!1),l=Qt(a.shape,e,r,!1);return a.reshape(s).transpose(u).reshape(l)},t.prototype.pool=function(t,e,n){this.assertNotComplex(t,"pool");for(var r=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,p="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,h=t.dataSync(),f=Po(e.outShape,t.dtype),d=f.values,m=e.outShape[1]*e.outShape[2]*e.outShape[3],g=e.outShape[2]*e.outShape[3],y=e.outShape[3],v=0;v<e.batchSize;++v)for(var b=v*m,w=v*t.strides[0],x=0;x<e.inChannels;++x)for(var N=0;N<e.outHeight;++N)for(var S=N*r-l,C=Math.max(0,S),E=Math.min(e.inHeight,s+S),I=b+N*g,k=0;k<e.outWidth;++k){for(var A=k*i-c,T=Math.max(0,A),R=Math.min(e.inWidth,u+A),D=p,O=0,_=0,M=C;M<E;M+=o){for(var L=w+M*t.strides[1],F=T;F<R;F+=a){var z=h[L+F*t.strides[2]+x];"max"===n&&z>D?D=z:"avg"===n&&(O+=z,_++)}if(isNaN(D))break}d[I+k*y+x]="avg"===n?O/_:D}return f.toTensor()},t.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},t.prototype.maxPoolPositions=function(t,e){for(var n=Po(e.outShape,"int32"),r=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,p=t.bufferSync(),h=0;h<e.batchSize;++h)for(var f=0;f<e.inChannels;++f)for(var d=0;d<e.outHeight;++d){for(var m=d*r-l,g=m;g<0;)g+=o;for(var y=Math.min(e.inHeight,s+m),v=0;v<e.outWidth;++v){for(var b=v*i-c,w=b;w<0;)w+=a;for(var x=Math.min(e.inWidth,u+b),N=Number.NEGATIVE_INFINITY,S=-1,C=g;C<y;C+=o)for(var E=C-m,I=w;I<x;I+=a){var k=I-b,A=p.get(h,C,I,f);A>N&&(N=A,S=E*u+k)}n.set(S,h,d,v,f)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var i=this.maxPoolPositions(e,r),o=r.strideHeight,a=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,p=c-1-r.padInfo.left,h=l-1-r.padInfo.top,f=Po(e.shape,"float32"),d=i.bufferSync(),m=t.bufferSync(),g=0;g<r.batchSize;++g)for(var y=0;y<r.inChannels;++y)for(var v=0;v<r.inHeight;++v)for(var b=0;b<r.inWidth;++b){for(var w=v-h,x=b-p,N=0,S=0;S<l;S+=s){var C=(w+S)/o;if(!(C<0||C>=r.outHeight||Math.floor(C)!==C))for(var E=0;E<c;E+=u){var I=(x+E)/a;if(!(I<0||I>=r.outWidth||Math.floor(I)!==I)){var k=l*c-1-d.get(g,C,I,y)===S*c+E?1:0;0!==k&&(N+=m.get(g,C,I,y)*k)}}}f.set(N,g,v,b,y)}return f.toTensor()},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,p=c-1-n.padInfo.left,h=l-1-n.padInfo.top,f=Po(e.shape,"float32"),d=1/(o*a),m=t.bufferSync(),g=0;g<n.batchSize;++g)for(var y=0;y<n.inChannels;++y)for(var v=0;v<n.inHeight;++v)for(var b=0;b<n.inWidth;++b){for(var w=v-h,x=b-p,N=0,S=0;S<l;S+=s){var C=(w+S)/r;if(!(C<0||C>=n.outHeight||Math.floor(C)!==C))for(var E=0;E<c;E+=u){var I=(x+E)/i;I<0||I>=n.outWidth||Math.floor(I)!==I||(N+=m.get(g,C,I,y))}}f.set(N*d,g,v,b,y)}return f.toTensor()},t.prototype.cast=function(t,e){return Ke(t,e,this)},t.prototype.reshape=function(t,e){return $e(t,e)},t.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},t.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var i=t.shape,o=i[0],a=i[1],s=i[2],u=i[3],l=t.dataSync(),c=new Float32Array(v([o,e,n,u])),p=[r&&e>1?a-1:a,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=p[0]/h[0],m=p[1]/h[1],g=0;g<o;g++)for(var y=0;y<e;y++)for(var b=d*y,w=Math.floor(b),x=b-w,N=Math.min(a-1,Math.ceil(b)),S=g*t.strides[0]+w*t.strides[1],C=g*t.strides[0]+N*t.strides[1],E=0;E<n;E++)for(var I=m*E,k=Math.floor(I),A=I-k,T=Math.min(s-1,Math.ceil(I)),R=S+k*t.strides[2],D=C+k*t.strides[2],O=S+ +T*t.strides[2],_=C+T*t.strides[2],M=0;M<u;M++){var L=l[R+M],F=l[D+M],z=L+(l[O+M]-L)*A,P=z+(F+(l[_+M]-F)*A-z)*x;c[f++]=P}return Re(c,[o,e,n,u])},t.prototype.resizeBilinearBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeBilinearBackprop");for(var r=e.shape,i=r[0],o=r[1],a=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],p=new Float32Array(i*o*a*s),h=[n&&l>1?o-1:o,n&&c>1?a-1:a],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=h[0]/f[0],m=h[1]/f[1],g=t.dataSync(),y=0,v=0;v<i;v++)for(var b=v*e.strides[0],w=0;w<l;w++)for(var x=w*d,N=Math.floor(x),S=Math.min(Math.ceil(x),o-1),C=b+N*e.strides[1],E=b+S*e.strides[1],I=x-N,k=1-I,A=0;A<c;A++)for(var T=A*m,R=Math.floor(T),D=Math.min(Math.ceil(T),a-1),O=T-R,_=1-O,M=C+R*e.strides[2],L=C+D*e.strides[2],F=E+R*e.strides[2],z=E+D*e.strides[2],P=k*_,B=k*O,U=I*_,W=I*O,V=0;V<s;V++){var j=g[y++];p[M+V]+=j*P,p[L+V]+=j*B,p[F+V]+=j*U,p[z+V]+=j*W}return Le(p,[i,a,o,s],e.dtype)},t.prototype.resizeNearestNeighbor=function(t,e,n,r){this.assertNotComplex(t,"resizeNearestNeighbor");for(var i=t.shape,o=i[0],a=i[1],s=i[2],u=i[3],l=t.dataSync(),c=new Float32Array(o*e*n*u),p=[r&&e>1?a-1:a,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=p[0]/h[0],d=p[1]/h[1],m=0,g=0;g<o;g++)for(var y=g*t.strides[0],v=0;v<e;v++)for(var b=f*v,w=y+Math.min(a-1,r?Math.round(b):Math.floor(b))*t.strides[1],x=0;x<n;x++)for(var N=d*x,S=w+Math.min(s-1,r?Math.round(N):Math.floor(N))*t.strides[2],C=0;C<u;C++){var E=l[S+C];c[m++]=E}return Re(c,[o,e,n,u],t.dtype)},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,i=r[0],o=r[1],a=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],p=new Float32Array(i*o*a*s),h=t.dataSync(),f=[n&&l>1?o-1:o,n&&c>1?a-1:a],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=f[0]/d[0],g=f[1]/d[1],y=1/m,v=1/g,b=2*Math.ceil(y)+2,w=2*Math.ceil(v)+2,x=0;x<i;x++)for(var N=x*e.strides[0],S=0;S<o;S++)for(var C=N+S*e.strides[1],E=Math.floor(S*y),I=Math.floor(E-b/2),k=0;k<a;k++)for(var A=C+k*e.strides[2],T=Math.floor(k*v),R=Math.floor(T-w/2),D=0;D<s;D++){for(var O=0,_=0;_<b;_++){var M=_+I;if(!(M<0||M>=l)){var L=N+M*t.strides[1],F=M*m;if(S===Math.min(o-1,n?Math.round(F):Math.floor(F)))for(var z=0;z<w;z++){var P=z+R;if(!(P<0||P>=c)){var B=L+P*t.strides[2],U=P*g;k===Math.min(a-1,n?Math.round(U):Math.floor(U))&&(O+=h[B+D])}}}}p[A+D]=O}return Le(p,e.shape,e.dtype)},t.prototype.batchNormalization=function(t,e,n,r,i,o){this.assertNotComplex([t,e,n,i,o],"batchNorm");for(var a=t.dataSync(),s=e.dataSync(),u=n.dataSync(),l=i?i.dataSync():new Float32Array([1]),c=o?o.dataSync():new Float32Array([0]),p=new Float32Array(a.length),h=c.length,f=l.length,d=u.length,m=s.length,g=0,y=0,v=0,b=0,w=0;w<a.length;++w)p[w]=c[g++]+(a[w]-s[y++])*l[v++]/Math.sqrt(u[b++]+r),g>=h&&(g=0),y>=m&&(y=0),v>=f&&(v=0),b>=d&&(b=0);return Le(p,t.shape)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){this.assertNotComplex(t,"localResponseNormalization4D");var o=t.shape[3],a=o-1,s=t.dataSync(),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%o,r=t-n+Math.max(0,n-e),i=t-n+Math.min(n+e,a),u=0;r<=i;r++){var l=s[r];u+=l*l}return u}for(var p=0;p<u;p++){var h=c(p),f=s[p]*Math.pow(n+r*h,-i);l[p]=f}return Le(l,t.shape)},t.prototype.LRNGrad=function(t,e,n,r,i,o,a){this.assertNotComplex(t,"LRNGrad");for(var s=t.shape[3],u=t.dataSync(),l=e.dataSync(),c=n.dataSync(),p=new Float32Array(t.size),h=t.size,f=0;f<h;f++){for(var d=f%s,m=f-d+Math.max(0,d-r),g=f-d+Math.min(s,d+r+1),y=0,v=m;v<g;v++)y+=Math.pow(l[v],2);for(y=o*y+i,v=m;v<g;v++){var b=-2*o*a*l[v]*c[f]/y;f===v&&(b+=Math.pow(y,-a)),b*=u[f],p[v]+=b}}return Le(p,t.shape)},t.prototype.multinomial=function(t,e,n,r){this.assertNotComplex(t,"multinomial");for(var i=e?t:Ee(t),o=i.shape[0],a=i.shape[1],s=Be([o,n],"int32"),u=s.dataSync(),l=i.dataSync(),c=0;c<o;++c){var p=c*a,h=new Float32Array(a-1);h[0]=l[p];for(var f=1;f<h.length;++f)h[f]=h[f-1]+l[p+f];for(var d=Fo(r.toString()),m=c*n,g=0;g<n;++g){var y=d();u[m+g]=h.length;for(var v=0;v<h.length;v++)if(y<h[v]){u[m+g]=v;break}}}return s},t.prototype.oneHot=function(t,e,n,r){this.assertNotComplex(t,"oneHot");var i=new Float32Array(t.size*e);i.fill(r);for(var o=t.dataSync(),a=0;a<t.size;++a)o[a]>=0&&o[a]<e&&(i[a*e+o[a]]=n);return _e(i,[t.size,e],"int32")},t.prototype.nonMaxSuppression=function(t,e,n,r,i){return this.assertNotComplex(t,"nonMaxSuppression"),Qe(t.dataSync(),e.dataSync(),n,r,i)},t.prototype.fft=function(t){return this.fftBatch(t,!1)},t.prototype.ifft=function(t){return this.fftBatch(t,!0)},t.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],i=Po(t.shape,"float32"),o=Po(t.shape,"float32"),a=Ae(t).as2D(n,r),s=Te(t).as2D(n,r),u=0;u<n;u++)for(var l=a.slice([u,0],[1,r]),c=s.slice([u,0],[1,r]),p=ke(l,c),h=this.fftImpl(p,e).dataSync(),f=0;f<r;f++){var d=Ye(h,f);i.values[u*r+f]=d.real,o.values[u*r+f]=d.imag}return ke(i.toTensor(),o.toTensor()).as2D(n,r)},t.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var i=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(i=ke(Ae(i).div(De(r)),Te(i).div(De(r)))),i}var o=t.dataSync(),a=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(o,r,e));return ke(a.real,a.imag).as2D(t.shape[0],t.shape[1])},t.prototype.isExponentOf2=function(t){return 0==(t&t-1)},t.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=t.dataSync(),i=e/2,o=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),i=0;i<t.length;i+=4)n[Math.floor(i/4)]=t[i],r[Math.floor(i/4)]=t[i+1];return{real:n,imag:r}}(r),a=ke(o.real,o.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),i=2;i<t.length;i+=4)n[Math.floor(i/4)]=t[i],r[Math.floor(i/4)]=t[i+1];return{real:n,imag:r}}(r),u=ke(s.real,s.imag).as1D();a=this.fftRadix2(a,i,n),u=this.fftRadix2(u,i,n);var l=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),i=0;i<Math.ceil(t/2);i++){var o=(e?2:-2)*Math.PI*(i/t);n[i]=Math.cos(o),r[i]=Math.sin(o)}return{real:n,imag:r}}(e,n),c=ke(l.real,l.imag).mul(u),p=a.add(c),h=a.sub(c),f=Ae(p).concat(Ae(h)),d=Te(p).concat(Te(h));return ke(f,d).as1D()},t.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),i=0;i<e;i++){for(var o=0,a=0,s=0;s<e;s++){var u=Ze(i*s,e,n),l=Ye(t,s);o+=l.real*u.real-l.imag*u.imag,a+=l.real*u.imag+l.imag*u.real}n&&(o/=e,a/=e),Je(r,o,a,i)}return r},t.prototype.depthToSpace=function(t,e,n){d("NHWC"===n,function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n}),d(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],i=t.shape[1],o=t.shape[2],a=t.shape[3],s=i*e,u=o*e,l=a/(e*e),c=t.dataSync(),p=new Float32Array(r*s*u*l),h=0,f=0;f<r;++f)for(var m=0;m<s;++m)for(var g=Math.floor(m/e),y=m%e,v=0;v<u;++v)for(var b=Math.floor(v/e),w=(y*e+v%e)*l,x=0;x<l;++x){var N=x+w+a*(b+o*(g+i*f));p[h++]=c[N]}return Le(p,[r,s,u,l])},t.prototype.broadcastedBinaryOp=function(t,e,n,r){var i=ln(t.shape,e.shape),o=Po(i,n),a=t.dataSync(),s=e.dataSync(),u=sn(t.shape,i),l=sn(e.shape,i),c=o.values;if(u.length+l.length===0)for(var p=0;p<c.length;++p)c[p]=r(a[p%a.length],s[p%s.length]);else{var h=t.bufferSync(),f=e.bufferSync(),d=function(n){var i=o.indexToLoc(n),p=i.slice(-t.rank);u.forEach(function(t){return p[t]=0});var d=h.locToIndex(p),m=i.slice(-e.rank);l.forEach(function(t){return m[t]=0});var g=f.locToIndex(m);c[n]=r(a[d],s[g])};for(p=0;p<c.length;++p)d(p)}return o.toTensor()},t.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=ln(t.shape,e.shape),i=Po(r,"float32"),o=Po(r,"float32"),a=t.dataSync(),s=e.dataSync(),u=sn(t.shape,r),l=sn(e.shape,r),c=i.values,p=o.values;if(u.length+l.length===0)for(var h=0;h<c.length;h++){var f=h%a.length,d=h%s.length,m=n(a[2*f],a[2*f+1],s[2*d],s[2*d+1]);c[h]=m.real,p[h]=m.imag}else{var g=this.data.get(t.dataId).complexTensors.real.bufferSync(),y=this.data.get(e.dataId).complexTensors.real.bufferSync(),v=function(r){var o=i.indexToLoc(r),h=o.slice(-t.rank);u.forEach(function(t){return h[t]=0});var f=g.locToIndex(h),d=o.slice(-e.rank);l.forEach(function(t){return d[t]=0});var m=y.locToIndex(d),v=n(a[2*f],a[2*f+1],s[2*m],s[2*m+1]);c[r]=v.real,p[r]=v.imag};for(h=0;h<c.length;h++)v(h)}return this.complex(i.toTensor(),o.toTensor())},t.prototype.split=function(t,e,n){return en(t,e,n)},t.prototype.dispose=function(){},t.prototype.floatPrecision=function(){return 32},t.prototype.cropAndResize=function(t,e,n,r,i,o){for(var a=t.shape,s=a[0],u=a[1],l=a[2],c=a[3],p=e.shape[0],h=r[0],f=r[1],d=Po([p,h,f,c],t.dtype),m=e.dataSync(),g=n.dataSync(),y=t.dataSync(),v=t.strides,b=d.strides,w=0;w<p;w++){var x=4*w,N=m[x],S=m[x+1],C=m[x+2],E=m[x+3],I=g[w];if(!(I>=s))for(var k=h>1?(C-N)*(u-1)/(h-1):0,A=f>1?(E-S)*(l-1)/(f-1):0,T=0;T<h;T++){var R=h>1?N*(u-1)+T*k:.5*(N+C)*(u-1);if(R<0||R>u-1)for(var D=0;D<f;D++)for(var O=0;O<c;O++){var _=O+D*b[2]+T*b[1]+w*b[0];d.values[_]=o}else if("bilinear"===i){var M=Math.floor(R),L=Math.ceil(R),F=R-M;for(D=0;D<f;D++)if((G=f>1?S*(l-1)+D*A:.5*(S+E)*(l-1))<0||G>l-1)for(O=0;O<c;O++)_=O+D*b[2]+T*b[1]+w*b[0],d.values[_]=o;else{var z=Math.floor(G),P=Math.ceil(G),B=G-z;for(O=0;O<c;O++){var U=y[_=O+z*v[2]+M*v[1]+I*v[0]],W=y[_=O+P*v[2]+M*v[1]+I*v[0]],V=y[_=O+z*v[2]+L*v[1]+I*v[0]],j=U+(W-U)*B,q=V+(y[_=O+P*v[2]+L*v[1]+I*v[0]]-V)*B;_=O+D*b[2]+T*b[1]+w*b[0],d.values[_]=j+(q-j)*F}}}else for(D=0;D<f;++D){var G;if((G=f>1?S*(l-1)+D*A:.5*(S+E)*(l-1))<0||G>l-1)for(O=0;O<c;O++)_=O+D*b[2]+T*b[1]+w*b[0],d.values[_]=o;else{var H=Math.round(G),K=Math.round(R);for(O=0;O<c;O++){var $=O+H*v[2]+K*v[1]+I*v[0],X=O+D*b[2]+T*b[1]+w*b[0];d.values[X]=y[$]}}}}}return d.toTensor()},t.prototype.sparseToDense=function(t,e,n,r){var i=de(0,t,n),o=i.sliceRank,a=i.numUpdates,s=i.sliceSize,u=i.strides,l=i.outputSize;return this.scatter(t,e,n,l,s,a,o,u,r,!1)},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=ce(t,e),o=i[0],a=i[1],s=i[2],u=i[3];if(0===a)return Re([],o,t.dtype);for(var l=new ot([a,s],t.dtype),c=e.dataSync(),p=t.dataSync(),h=0;h<a;h++){for(var f=[],d=0,m=0;m<r;m++){var g=c[h*r+m];d+=g*u[m],f.push(g)}if(d<0||d>=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var y=0;y<s;y++)l.values[h*s+y]=p[d*s+y]}return l.toTensor().reshape(o)},t.prototype.scatterND=function(t,e,n){var r=de(0,t,n),i=r.sliceRank,o=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,l=De(0);return this.scatter(t,e,n,u,a,o,i,s,l,!0)},t.prototype.fill=function(t,e,n){var r=T(n=n||B(e),v(t));return r.fill(e),lt.make(t,{values:r},n)},t.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype)},t.prototype.zerosLike=function(t){var e=T(t.dtype,v(t.shape));return lt.make(t.shape,{values:e},t.dtype)},t.prototype.scatter=function(t,e,n,r,i,o,a,s,u,l){var c=[r/i,i],p=t.dataSync(),h=e.dataSync();if(0===r)return Re([],n,e.dtype);var f=new ot(c,e.dtype);f.values.fill(u.dataSync()[0]);for(var d=0;d<o;d++){for(var m=[],g=0,y=0;y<a;y++){var v=p[d*a+y];m.push(v),g+=v*s[y]}if(g<0||g>=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b<i;b++)l?f.values[g*i+b]+=h[d*i+b]:f.values[g*i+b]=0===e.rank?h[0]:h[d*i+b]}return f.toTensor().reshape(n)},t}();Ut.registerBackend("cpu",function(){return new Ll},1);var Fl="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};function zl(){return new Promise(function(t){return Fl(function(){return t()})})}var Pl={float32:4,int32:4,uint16:2,uint8:1,bool:1};function Bl(t,e){for(var n={},r=0,i=function(e){var i=e.name,o=e.dtype,a=e.shape,s=v(a),u=void 0;if("quantization"in e){var l=e.quantization;if("uint8"!==l.dtype&&"uint16"!==l.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+l.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var c=Pl[l.dtype],p=t.slice(r,r+s*c),h="uint8"===l.dtype?new Uint8Array(p):new Uint16Array(p);if("float32"===o)u=Float32Array.from(h,function(t){return t*l.scale+l.min});else{if("int32"!==o)throw new Error("Unsupported dtype in weight '"+i+"': "+o);u=Int32Array.from(h,function(t){return Math.round(t*l.scale+l.min)})}r+=s*c}else{var f=Pl[o];if(p=t.slice(r,r+s*f),"float32"===o)u=new Float32Array(p);else if("int32"===o)u=new Int32Array(p);else{if("bool"!==o)throw new Error("Unsupported dtype in weight '"+i+"': "+o);u=new Uint8Array(p)}r+=s*f}var d=void 0;if("float32"===o)d=Re(u,a,"float32");else if("int32"===o)d=Re(u,a,"int32");else{if("bool"!==o)throw new Error("Unsupported dtype in weight '"+i+"': "+o);d=Re(u,a,"bool")}n[i]=d},o=0,a=e;o<a.length;o++)i(a[o]);return n}var Ul="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Wl(t){return Ul?Buffer.byteLength(t):new Blob([t]).size}function Vl(t){var e=0;t.forEach(function(t){e+=t.byteLength});var n=new Uint8Array(e),r=0;return t.forEach(function(t){n.set(new Uint8Array(t),r),r+=t.byteLength}),n.buffer}function jl(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function ql(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==t.modelTopology?0:Wl(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:Wl(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var Gl=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,r){var i=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach(function(t){var n=t(e,r);null!==n&&i.push(n)}),i},t}(),Hl="://",Kl=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){d(null!=e,function(){return"scheme must not be undefined or null."}),e.endsWith(Hl)&&(e=e.slice(0,e.indexOf(Hl))),d(e.length>0,function(){return"scheme must not be an empty string."});var r=t.getInstance();d(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function $l(t){if(-1===t.indexOf(Hl))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Kl.getSchemes().join(","));return{scheme:t.split(Hl)[0],path:t.split(Hl)[1]}}function Xl(t,e,n){return void 0===n&&(n=!1),i(this,void 0,void 0,function(){var r,i,a,s,u,l,c,p,h;return o(this,function(o){switch(o.label){case 0:return d(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),d((r=Gl.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),d(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),i=r[0],d((a=Gl.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),d(a.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=a[0],u=$l(t).scheme,l=$l(t).path,c=u===$l(t).scheme,[4,i.load()];case 1:return p=o.sent(),n&&c?[4,Kl.getManager(u).removeModel(l)]:[3,3];case 2:o.sent(),o.label=3;case 3:return[4,s.save(p)];case 4:return h=o.sent(),!n||c?[3,6]:[4,Kl.getManager(u).removeModel(l)];case 5:o.sent(),o.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}var Yl="models_store",Jl="model_info_store";function Zl(){if(!Ut.get("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Ql(t){var e=t.result;e.createObjectStore(Yl,{keyPath:"modelPath"}),e.createObjectStore(Jl,{keyPath:"modelPath"})}var tc=function(){function t(t){if(this.indexedDB=Zl(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){return o(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},t.prototype.load=function(){return i(this,void 0,void 0,function(){return o(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Ql(i)},i.onsuccess=function(){var o=i.result;if(null==e){var a=o.transaction(Yl,"readonly"),s=a.objectStore(Yl).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return o.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return o.close(),r(s.error)},a.oncomplete=function(){return o.close()}}else{var u,l=ql(e),c=o.transaction(Jl,"readwrite"),p=c.objectStore(Jl),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:l});h.onsuccess=function(){var i=(u=o.transaction(Yl,"readwrite")).objectStore(Yl).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});i.onsuccess=function(){return t({modelArtifactsInfo:l})},i.onerror=function(t){var e=(p=c.objectStore(Jl)).delete(n.modelPath);e.onsuccess=function(){return o.close(),r(i.error)},e.onerror=function(t){return o.close(),r(i.error)}}},h.onerror=function(t){return o.close(),r(h.error)},c.oncomplete=function(){null==u?o.close():u.oncomplete=function(){return o.close()}}}},i.onerror=function(t){return r(i.error)}})},t.URL_SCHEME="indexeddb://",t}(),ec=function(t){return Ut.get("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(tc.URL_SCHEME)?function(t){return new tc(t)}(t.slice(tc.URL_SCHEME.length)):null};Gl.registerSaveRouter(ec),Gl.registerLoadRouter(ec);var nc=function(){function t(){this.indexedDB=Zl()}return t.prototype.listModels=function(){return i(this,void 0,void 0,function(){var t=this;return o(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Ql(r)},r.onsuccess=function(){var t=r.result,i=t.transaction(Jl,"readonly"),o=i.objectStore(Jl).getAll();o.onsuccess=function(){for(var t={},n=0,r=o.result;n<r.length;n++){var i=r[n];t[i.modelPath]=i.modelArtifactsInfo}e(t)},o.onerror=function(e){return t.close(),n(o.error)},i.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}})]})})},t.prototype.removeModel=function(t){return i(this,void 0,void 0,function(){var e=this;return o(this,function(n){return t=function(t){return t.startsWith(tc.URL_SCHEME)?t.slice(tc.URL_SCHEME.length):t}(t),[2,new Promise(function(n,r){var i=e.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Ql(i)},i.onsuccess=function(){var e,o=i.result,a=o.transaction(Jl,"readwrite"),s=a.objectStore(Jl),u=s.get(t);u.onsuccess=function(){if(null==u.result)return o.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var i=s.delete(t),a=function(){var i=(e=o.transaction(Yl,"readwrite")).objectStore(Yl).delete(t);i.onsuccess=function(){return n(u.result.modelArtifactsInfo)},i.onerror=function(t){return r(u.error)}};i.onsuccess=a,i.onerror=function(t){return a(),o.close(),r(u.error)}},u.onerror=function(t){return o.close(),r(u.error)},a.oncomplete=function(){null==e?o.close():e.oncomplete=function(){return o.close()}}},i.onerror=function(t){return r(i.error)}})]})})},t}();if(Ut.get("IS_BROWSER"))try{Kl.registerManager(tc.URL_SCHEME,new nc)}catch(mt){}var rc="/",ic="tensorflowjs_models",oc="info",ac="model_topology",sc="weight_specs",uc="weight_data",lc="model_metadata";function cc(t){return{info:[ic,t,oc].join(rc),topology:[ic,t,ac].join(rc),weightSpecs:[ic,t,sc].join(rc),weightData:[ic,t,uc].join(rc),modelMetadata:[ic,t,lc].join(rc)}}function pc(t){var e=t.split(rc);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(rc)}var hc=function(){function t(t){if(!Ut.get("IS_BROWSER")||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=cc(this.modelPath)}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){var e,n,r,i;return o(this,function(o){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),r=ql(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(t){return Ul?Buffer.from(t).toString("base64"):btoa(String.fromCharCode.apply(null,new Uint8Array(t)))}(t.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy})),[2,{modelArtifactsInfo:r}]}catch(t){for(i in this.keys)this.LS.removeItem(this.keys[i]);throw new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+r.modelTopologyBytes+", weightSpecsBytes="+r.weightSpecsBytes+", weightDataBytes="+r.weightDataBytes+".")}return[2]})})},t.prototype.load=function(){return i(this,void 0,void 0,function(){var t,e,n,r,i,a,s;return o(this,function(o){if(null==(t=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,null==(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=r,null!=(i=this.LS.getItem(this.keys.modelMetadata))&&(a=JSON.parse(i),e.format=a.format,e.generatedBy=a.generatedBy,e.convertedBy=a.convertedBy),null==(s=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(t){if(Ul){var e=Buffer.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}for(var n=atob(t),r=new Uint8Array(n.length),i=0;i<n.length;++i)r.set([n.charCodeAt(i)],i);return r.buffer}(s),[2,e]})})},t.URL_SCHEME="localstorage://",t}(),fc=function(t){return Ut.get("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(hc.URL_SCHEME)?function(t){return new hc(t)}(t.slice(hc.URL_SCHEME.length)):null};Gl.registerSaveRouter(fc),Gl.registerLoadRouter(fc);var dc=function(){function t(){d(Ut.get("IS_BROWSER"),function(){return"Current environment is not a web browser"}),d(void 0!==window.localStorage,function(){return"Current browser does not appear to support localStorage"}),this.LS=window.localStorage}return t.prototype.listModels=function(){return i(this,void 0,void 0,function(){var t,e,n,r,i,a;return o(this,function(o){for(t={},e=ic+rc,n=rc+oc,r=0;r<this.LS.length;++r)(i=this.LS.key(r)).startsWith(e)&&i.endsWith(n)&&(a=pc(i),t[a]=JSON.parse(this.LS.getItem(i)));return[2,t]})})},t.prototype.removeModel=function(t){return i(this,void 0,void 0,function(){var e,n;return o(this,function(r){if(t=function(t){return t.startsWith(hc.URL_SCHEME)?t.slice(hc.URL_SCHEME.length):t}(t),e=cc(t),null==this.LS.getItem(e.info))throw new Error("Cannot find model at path '"+t+"'");return n=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,n]})})},t}();if(Ut.get("IS_BROWSER"))try{Kl.registerManager(hc.URL_SCHEME,new dc)}catch(mt){}var mc="model",gc=".json",yc=".weights.bin",vc=function(){function t(e){if(!Ut.get("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(t.URL_SCHEME)&&(e=e.slice(t.URL_SCHEME.length)),null!=e&&0!==e.length||(e=mc),this.modelTopologyFileName=e+gc,this.weightDataFileName=e+yc}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){var e,n,r,i,a,s;return o(this,function(o){if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},i=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(a=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,a.href=i,a.click(),null!=t.weightData&&((s=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,s.click()),[2,{modelArtifactsInfo:ql(t)}]})})},t.URL_SCHEME="downloads://",t}(),bc=function(){function t(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return t.prototype.load=function(){return i(this,void 0,void 0,function(){var t,e,n=this;return o(this,function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise(function(r,i){var o=new FileReader;o.onload=function(o){var a=JSON.parse(o.target.result),s=a.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=a.weightsManifest;if(null!=u){var l;try{l=n.checkManifestAndWeightFiles(u,e)}catch(t){return void i(t)}var c=[],p=[],h=[];u.forEach(function(t){t.paths.forEach(function(t){p.push(t),h.push(null)}),c.push.apply(c,t.weights)}),u.forEach(function(t){t.paths.forEach(function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,i=p.indexOf(t);h[i]=n,-1===h.indexOf(null)&&r({modelTopology:s,weightSpecs:c,weightData:Vl(h)})},e.onerror=function(e){return i("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(l[t])})})}else i(new Error("weightManifest field is missing from file "+t.name))}else i(new Error("modelTopology field is missing from file "+t.name))},o.onerror=function(e){return i("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},o.readAsText(t)})]})})},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map(function(t){return jl(t.name)}),i={},o=0,a=t;o<a.length;o++)a[o].paths.forEach(function(t){var o=jl(t);if(-1!==n.indexOf(o))throw new Error("Duplicate file basename found in weights manifest: '"+o+"'");if(n.push(o),-1===r.indexOf(o))throw new Error("Weight file with basename '"+o+"' is not provided.");i[t]=e[r.indexOf(o)]});if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return i},t}();function wc(t,e,n,r){!function(t){d(null!=t&&Array.isArray(t)&&t.length>0,function(){return"promises must be a none empty array"})}(t),function(t,e){d(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),d(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),d(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var i=0;return Promise.all(t.map(function(o){return o.then(function(o){var a=n+ ++i/t.length*(r-n);return e(a),o}),o}))}function xc(t,e){return i(this,void 0,void 0,function(){var n,r,i,a,s,u,l,c,p;return o(this,function(o){switch(o.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?fetch:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit)}),i=0,a=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return s=o.sent(),[3,4];case 2:return[4,wc(r,e.onProgress,i,a)];case 3:s=o.sent(),o.label=4;case 4:return u=s.map(function(t){return t.arrayBuffer()}),l=.5,c=1,null!=e.onProgress?[3,6]:[4,Promise.all(u)];case 5:return p=o.sent(),[3,8];case 6:return[4,wc(u,e.onProgress,l,c)];case 7:p=o.sent(),o.label=8;case 8:return[2,p]}})})}function Nc(t){var e=this;return function(n,r,a){return void 0===r&&(r=""),i(e,void 0,void 0,function(){var e,i,s,u,l,c,p,h,f,d;return o(this,function(o){switch(o.label){case 0:if(e=n.map(function(){return!1}),i={},s=null!=a?a.map(function(){return!1}):[],u=[],n.forEach(function(t,n){var r=0;t.weights.forEach(function(t){var o="quantization"in t?t.quantization.dtype:t.dtype,l=Pl[o]*v(t.shape),c=function(){e[n]=!0,null==i[n]&&(i[n]=[]),i[n].push({manifestEntry:t,groupOffset:r,sizeBytes:l})};null!=a?a.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),u.push(t.name),r+=l})}),!s.every(function(t){return t}))throw l=a.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),p=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=r+(r.endsWith("/")?"":"/")+t;p.push(e)})}),[4,t(p)];case 1:return h=o.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,r=0,o=0;o<e;o++)r+=h[d+o].byteLength;for(var a=new ArrayBuffer(r),s=new Uint8Array(a),u=0,l=0;l<e;l++){var c=new Uint8Array(h[d+l]);s.set(c,u),u+=c.byteLength}i[t].forEach(function(t){var e=Bl(a.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)f[n]=e[n]}),d+=e}),[2,f]}})})}}Gl.registerSaveRouter(function(t){return Ut.get("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(vc.URL_SCHEME)?function(t){return void 0===t&&(t="model"),new vc(t)}(t.slice(vc.URL_SCHEME.length)):null});var Sc=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null==e.fetchFunc){if("undefined"==typeof fetch)throw new Error("browserHTTPRequest is not supported outside the web browser without a fetch polyfill.");e.fetchFunc=fetch.bind("undefined"==typeof window?null:window)}else d("function"==typeof e.fetchFunc,function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"});if(this.fetchFunc=function(t,n){return e.fetchFunc(t,n).catch(function(e){throw new Error("Request for "+t+" failed due to error: "+e)})},d(null!=t&&t.length>0,function(){return"URL path for browserHTTPRequest must not be null, undefined or empty."}),Array.isArray(t)&&d(2===t.length,function(){return"URL paths for browserHTTPRequest must have a length of 2, (actual length is "+t.length+")."}),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){var e,n,r,i;return o(this,function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.getFetchFunc()(this.path,e)];case 1:if((i=o.sent()).ok)return[2,{modelArtifactsInfo:ql(t),responses:[i]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+i.status+".")}})})},t.prototype.load=function(){return i(this,void 0,void 0,function(){var t,e,n,r,i,a,s,u;return o(this,function(o){switch(o.label){case 0:return[4,this.getFetchFunc()(this.path,this.requestInit)];case 1:if(!(t=o.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");o.label=2;case 2:return o.trys.push([2,4,,5]),[4,t.json()];case 3:return e=o.sent(),[3,5];case 4:throw o.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,i=e.weightsManifest,null==r&&null==i)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==i?[3,7]:[4,this.loadWeights(i)];case 6:u=o.sent(),a=u[0],s=u[1],o.label=7;case 7:return[2,{modelTopology:r,weightSpecs:a,weightData:s}]}})})},t.prototype.loadWeights=function(t){return i(this,void 0,void 0,function(){var e,n,r,i,a,s,u,l,c,p,h;return o(this,function(o){switch(o.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],i=n[1],a=this.weightPathPrefix||r,s=[],u=0,l=t;u<l.length;u++)c=l[u],s.push.apply(s,c.weights);return p=[],t.forEach(function(t){t.paths.forEach(function(t){p.push(a+t+i)})}),[4,xc(p,{requestInit:this.requestInit,fetchFunc:this.getFetchFunc(),onProgress:this.onProgress})];case 1:return h=o.sent(),[2,[s,Vl(h)]]}})})},t.prototype.getFetchFunc=function(){return this.fetchFunc},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function Cc(t){return null!=t.match(Sc.URL_SCHEME_REGEX)}var Ec=function(t,e){return"undefined"==typeof fetch?null:(Array.isArray(t)?t.every(function(t){return Cc(t)}):Cc(t))?Ic(t,{onProgress:e}):null};function Ic(t,e){return new Sc(t,e)}Gl.registerSaveRouter(Ec),Gl.registerLoadRouter(Ec);var kc=function(){function t(t,e,n){this.modelTopology=t,this.weightSpecs=e,this.weightData=n}return t.prototype.load=function(){return i(this,void 0,void 0,function(){var t;return o(this,function(e){return t={},null!=this.modelTopology&&(t=r({modelTopology:this.modelTopology},t)),null!=this.weightSpecs&&this.weightSpecs.length>0&&(t=r({weightSpecs:this.weightSpecs},t)),null!=this.weightData&&this.weightData.byteLength>0&&(t=r({weightData:this.weightData},t)),[2,t]})})},t}(),Ac=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return i(this,void 0,void 0,function(){return o(this,function(e){return[2,this.saveHandler(t)]})})},t}();var Tc=Object.freeze({browserFiles:function(t){return new bc(t)},browserHTTPRequest:Ic,concatenateArrayBuffers:Vl,decodeWeights:Bl,encodeWeights:function(t){return i(this,void 0,void 0,function(){var e,n,r,i;return o(this,function(o){switch(o.label){case 0:for(r in e=[],n=[],t){if("float32"!==(i=t[r]).dtype&&"int32"!==i.dtype&&"bool"!==i.dtype)throw new Error("Unsupported dtype in weight '"+r+"': "+i.dtype);e.push({name:r,shape:i.shape,dtype:i.dtype}),n.push(i.data())}return[4,Promise.all(n)];case 1:return[2,{data:function(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach(function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)});var r=new Uint8Array(e),i=0;return n.forEach(function(t){r.set(new Uint8Array(t.buffer),i),i+=t.byteLength}),r.buffer}(o.sent()),specs:e}]}})})},fromMemory:function(t,e,n){return new kc(t,e,n)},getLoadHandlers:function(t,e){return Gl.getLoadHandlers(t)},getModelArtifactsInfoForJSON:ql,getSaveHandlers:function(t){return Gl.getSaveHandlers(t)},isHTTPScheme:Cc,loadWeights:function(t,e,n,r){return void 0===e&&(e=""),i(this,void 0,void 0,function(){return o(this,function(i){return[2,Nc(function(t){return xc(t,{requestInit:r})})(t,e,n)]})})},registerLoadRouter:function(t){return Gl.registerLoadRouter(t)},registerSaveRouter:function(t){return Gl.registerSaveRouter(t)},weightsLoaderFactory:Nc,withSaveHandler:function(t){return new Ac(t)},copyModel:function(t,e){return i(this,void 0,void 0,function(){return o(this,function(n){switch(n.label){case 0:return[4,Xl(t,e,!1)];case 1:return[2,n.sent()]}})})},listModels:function(){return i(this,void 0,void 0,function(){var t,e,n,r,i,a,s;return o(this,function(o){switch(o.label){case 0:t=Kl.getSchemes(),e={},n=0,r=t,o.label=1;case 1:return n<r.length?(i=r[n],[4,Kl.getManager(i).listModels()]):[3,4];case 2:for(s in a=o.sent())e[i+Hl+s]=a[s];o.label=3;case 3:return n++,[3,1];case 4:return[2,e]}})})},moveModel:function(t,e){return i(this,void 0,void 0,function(){return o(this,function(n){switch(n.label){case 0:return[4,Xl(t,e,!0)];case 1:return[2,n.sent()]}})})},removeModel:function(t){return i(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return e=$l(t),[4,Kl.getManager(e.scheme).removeModel(e.path)];case 1:return[2,n.sent()]}})})}});var Rc=Ce({confusionMatrix_:function(t,e,n){var r=Ne(t,"labels","confusionMatrix"),i=Ne(e,"predictions","confusionMatrix");d(null==n||n>0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),d(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),d(1===i.rank,function(){return"Expected the rank of predictions to be 1, but got "+i.rank}),d(r.shape[0]===i.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+i.shape[0]+". Labels and predictions should have the same number of elements."}),d(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var o=$o(r.asType("int32"),n),a=$o(i.asType("int32"),n);return o.transpose().matMul(a).asType("int32")}}),Dc=Object.freeze({confusionMatrix:Rc});var Oc=Ce({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return Ut.engine.fromPixels(t,e)}}),_c=Object.freeze({toPixels:function(t,e){return i(this,void 0,void 0,function(){var n,r,i,a,s,u,l,c,p,h,f,d,m,g,y,v,b,w,x,N;return o(this,function(o){switch(o.label){case 0:if(n=Ne(t,"img","toPixels"),t instanceof lt||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),i=r[0],a=r[1],(s=2===n.rank?1:n.shape[2])>4||2===s)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+s);return u=n.min(),l=n.max(),[4,u.data()];case 1:return c=o.sent()[0],[4,l.data()];case 2:if(p=o.sent()[0],u.dispose(),l.dispose(),"float32"===n.dtype){if(c<0||p>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+c+" - "+p+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(c<0||p>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+c+" - "+p+"].")}return[4,n.data()];case 3:for(h=o.sent(),f="float32"===n.dtype?255:1,d=new Uint8ClampedArray(a*i*4),m=0;m<i*a;++m)g=void 0,y=void 0,v=void 0,b=void 0,1===s?(g=h[m]*f,y=h[m]*f,v=h[m]*f,b=255):3===s?(g=h[3*m]*f,y=h[3*m+1]*f,v=h[3*m+2]*f,b=255):4===s&&(g=h[4*m]*f,y=h[4*m+1]*f,v=h[4*m+2]*f,b=h[4*m+3]*f),d[0+(w=4*m)]=Math.round(g),d[w+1]=Math.round(y),d[w+2]=Math.round(v),d[w+3]=Math.round(b);return null!=e&&(e.width=a,e.height=i,x=e.getContext("2d"),N=new ImageData(d,a,i),x.putImageData(N,0,0)),n!==t&&n.dispose(),[2,d]}})})},fromPixels:Oc}),Mc=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),Lc=function(){function t(){this.classNameMap={}}return t.getMap=function(){return null==t.instance&&(t.instance=new t),t.instance},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig]},t}();function Fc(t){d(null!=t.className,function(){return"Class being registered does not have the static className property defined."}),d("string"==typeof t.className,function(){return"className is required to be a string, but got type "+typeof t.className}),d(t.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Lc.register(t)}var zc=Object.freeze({Serializable:Mc,SerializationMap:Lc,registerClass:Fc});function Pc(t,e,n){return null==n&&(n=Ut.get("TEST_EPSILON")),Bc(t,"number"==typeof e||"boolean"==typeof e?[e]:e,function(t,e){return Uc(t,Number(e),n)})}function Bc(t,e,n){if(t instanceof lt||e instanceof lt){if(t instanceof lt&&e instanceof lt){if(t.dtype!==e.dtype)throw new Error("Arrays are of different type actual: "+t.dtype+" vs expected: "+e.dtype+".");if(!b(t.shape,e.shape))throw new Error("Arrays are of different shape actual: "+t.shape+" vs expected: "+e.shape+".")}}else{var r=t.constructor.name,i=e.constructor.name;if(r!==i)throw new Error("Arrays are of different type actual: "+r+" vs expected: "+i)}var o,a;if(o=t instanceof lt?t.dataSync():t,a=e instanceof lt?e.dataSync():e,o.length!==a.length)throw new Error("Arrays have different lengths actual: "+o.length+" vs expected: "+a.length+".\nActual:   "+o+".\nExpected: "+a+".");for(var s=0;s<a.length;++s){var u=o[s],l=a[s];if(!n(u,l))throw new Error("Arrays differ: actual["+s+"] = "+u+", expected["+s+"] = "+l+".\nActual:   "+o+".\nExpected: "+a+".")}}function Uc(t,e,n){return!(!isNaN(t)||!isNaN(e))||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var Wc=Object.freeze({WEBGL_ENVS:{HAS_WEBGL:!0},PACKED_ENVS:{WEBGL_PACK:!0},NODE_ENVS:{IS_NODE:!0},CHROME_ENVS:{IS_CHROME:!0},BROWSER_ENVS:{IS_BROWSER:!0},CPU_ENVS:{HAS_WEBGL:!1},ALL_ENVS:{},expectArraysClose:Pc,expectPromiseToFail:function(t,e){t().then(function(){return e.fail()},function(){return e()})},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return t instanceof lt&&"string"===t.dtype||e instanceof lt&&"string"===e.dtype||Array.isArray(t)&&F(t[0])||Array.isArray(e)&&F(e[0])?Bc(t,n,function(t,e){return t==e}):Pc(t,e,0)},expectNumbersClose:function(t,e,n){if(null==n&&(n=Ut.get("TEST_EPSILON")),!Uc(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){var r;r=t instanceof lt?t.dataSync():t;for(var i=0;i<r.length;i++)if(r[i]<e||r[i]>n)throw new Error("Value out of range:"+r[i]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),Vc=Object.freeze({gpgpu_util:Si,webgl_util:ei,MathBackendWebGL:ha,GPGPUContext:Ci}),jc=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),i=r.value,o=r.grads;return this.applyGradients(o),Object.keys(o).forEach(function(t){return o[t].dispose()}),e?i:(i.dispose(),null)},e.prototype.computeGradients=function(t,e){return Vt(t,e)},e.prototype.dispose=function(){},e}(Mc);Object.defineProperty(jc,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var qc=function(t){function e(e,n,r){void 0===r&&(r=null);var i=t.call(this)||this;return i.learningRate=e,i.rho=n,i.epsilon=r,i.accumulatedGrads={},i.accumulatedUpdates={},i.c=Ht(De(-e)),i.rhoScalar=Ht(De(n)),i.oneMinusRho=Ht(De(1-n)),null===r&&(r=Ut.get("EPSILON")),i.epsilonScalar=Ht(De(r)),i}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Ut.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Gt(function(){e.accumulatedGrads[n]=qe(i).variable(!1)}),null==r.accumulatedUpdates[n]&&Gt(function(){e.accumulatedUpdates[n]=qe(i).variable(!1)});var o=t[n],a=r.accumulatedGrads[n],s=r.accumulatedUpdates[n];Gt(function(){var t=e.rhoScalar.mul(a).add(e.oneMinusRho.mul(o.square())),r=s.add(e.epsilonScalar).sqrt().div(a.add(e.epsilonScalar).sqrt()).mul(o),u=e.rhoScalar.mul(s).add(e.oneMinusRho.mul(r.square()));e.accumulatedGrads[n].assign(t),e.accumulatedUpdates[n].assign(u);var l=e.c.mul(r).add(i);i.assign(l)})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){var t=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(e){return t.accumulatedUpdates[e].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(e){return t.accumulatedGrads[e].dispose()}))},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="AdadeltaOptimizer",e}(jc);Fc(qc);var Gc=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads={},r.c=Ht(De(-e)),r.epsilon=Ht(De(Ut.get("EPSILON"))),r}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Ut.engine.registeredVariables[n];null==r.accumulatedGrads[n]&&Gt(function(){e.accumulatedGrads[n]=Ue(i.shape,e.initialAccumulatorValue).variable(!1)});var o=t[n],a=r.accumulatedGrads[n];Gt(function(){var t=a.add(o.square());e.accumulatedGrads[n].assign(t);var r=e.c.mul(o.div(t.add(e.epsilon).sqrt())).add(i);i.assign(r)})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){var t=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(e){return t.accumulatedGrads[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="AdagradOptimizer",e}(jc);Fc(Gc);var Hc=function(t){function e(e,n,r,i){void 0===i&&(i=null);var o=t.call(this)||this;return o.learningRate=e,o.beta1=n,o.beta2=r,o.epsilon=i,o.accumulatedFirstMoment={},o.accumulatedSecondMoment={},o.c=Ht(De(-e)),o.beta1Scalar=Ht(De(n)),o.beta2Scalar=Ht(De(r)),Gt(function(){o.accBeta1=De(n).variable(),o.accBeta2=De(r).variable()}),o.oneMinusBeta1=Ht(De(1-n)),o.oneMinusBeta2=Ht(De(1-r)),o.one=Ht(De(1)),null===i&&(i=Ut.get("EPSILON")),o.epsScalar=Ht(De(i)),o}return n(e,t),e.prototype.applyGradients=function(t){var e=this;Gt(function(){var n=e.one.sub(e.accBeta1),r=e.one.sub(e.accBeta2);for(var i in t){var o=Ut.engine.registeredVariables[i];if(null==e.accumulatedFirstMoment[i]){var a=!1;e.accumulatedFirstMoment[i]=qe(o).variable(a)}null==e.accumulatedSecondMoment[i]&&(a=!1,e.accumulatedSecondMoment[i]=qe(o).variable(a));var s=t[i],u=e.accumulatedFirstMoment[i],l=e.accumulatedSecondMoment[i],c=e.beta1Scalar.mul(u).add(e.oneMinusBeta1.mul(s)),p=e.beta2Scalar.mul(l).add(e.oneMinusBeta2.mul(s.square())),h=c.div(n),f=p.div(r);e.accumulatedFirstMoment[i].assign(c),e.accumulatedSecondMoment[i].assign(p);var d=e.c.mul(h.div(e.epsScalar.add(f.sqrt()))).add(o);o.assign(d)}e.accBeta1.assign(e.accBeta1.mul(e.beta1Scalar)),e.accBeta2.assign(e.accBeta2.mul(e.beta2Scalar))})},e.prototype.dispose=function(){var t=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(e){return t.accumulatedFirstMoment[e].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(e){return t.accumulatedSecondMoment[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="AdamOptimizer",e}(jc);Fc(Hc);var Kc=function(t){function e(e,n,r,i,o){void 0===i&&(i=null),void 0===o&&(o=0);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=i,a.decay=o,a.accumulatedFirstMoment={},a.accumulatedWeightedInfNorm={},a.c=Ht(De(-e)),a.beta1Scalar=Ht(De(n)),a.beta2Scalar=Ht(De(r)),a.decayScalar=Ht(De(o)),Gt(function(){a.iteration=De(0).variable(),a.accBeta1=De(n).variable()}),a.oneMinusBeta1=Ht(De(1-n)),a.one=Ht(De(1)),null===i&&(i=Ut.get("EPSILON")),a.epsScalar=Ht(De(i)),a}return n(e,t),e.prototype.applyGradients=function(t){var e=this;Gt(function(){var n=e.one.sub(e.accBeta1),r=e.c.div(e.one.add(e.decayScalar.mul(e.iteration)));for(var i in t){var o=Ut.engine.registeredVariables[i];if(null==e.accumulatedFirstMoment[i]){var a=!1;e.accumulatedFirstMoment[i]=qe(o).variable(a)}null==e.accumulatedWeightedInfNorm[i]&&(a=!1,e.accumulatedWeightedInfNorm[i]=qe(o).variable(a));var s=t[i],u=e.accumulatedFirstMoment[i],l=e.accumulatedWeightedInfNorm[i],c=e.beta1Scalar.mul(u).add(e.oneMinusBeta1.mul(s)),p=e.beta2Scalar.mul(l),h=s.abs(),f=p.maximum(h);e.accumulatedFirstMoment[i].assign(c),e.accumulatedWeightedInfNorm[i].assign(f);var d=r.div(n).mul(c.div(e.epsScalar.add(f))).add(o);o.assign(d)}e.iteration.assign(e.iteration.add(e.one)),e.accBeta1.assign(e.accBeta1.mul(e.beta1Scalar))})},e.prototype.dispose=function(){var t=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(e){return t.accumulatedFirstMoment[e].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(e){return t.accumulatedWeightedInfNorm[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="AdamaxOptimizer",e}(jc);Fc(Kc);var $c=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return n(e,t),e.prototype.applyGradients=function(t){var e=this;Object.keys(t).forEach(function(n){var r=t[n],i=Ut.engine.registeredVariables[n];Gt(function(){var t=e.c.mul(r).add(i);i.assign(t)})})},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Ht(De(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGDOptimizer",e}(jc);Fc($c);var Xc=function(t){function e(e,n,r){void 0===r&&(r=!1);var i=t.call(this,e)||this;return i.learningRate=e,i.momentum=n,i.useNesterov=r,i.m=De(i.momentum),i.accumulations={},i}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Ut.engine.registeredVariables[n];null==r.accumulations[n]&&Gt(function(){e.accumulations[n]=qe(i).variable(!1)});var o=r.accumulations[n],a=t[n];Gt(function(){var t,r=e.m.mul(o).add(a);t=e.useNesterov?e.c.mul(a.add(r.mul(e.m))).add(i):e.c.mul(r).add(i),e.accumulations[n].assign(r),i.assign(t)})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){if(t.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var e in this.accumulations)this.accumulations[e].dispose()},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="MomentumOptimizer",e}($c);Fc(Xc);var Yc=function(t){function e(e,n,r,i,o){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===i&&(i=null),void 0===o&&(o=!1);var a=t.call(this)||this;return a.learningRate=e,a.decay=n,a.momentum=r,a.epsilon=i,a.accumulatedMeanSquares={},a.accumulatedMeanGrads={},a.accumulatedMoments={},a.c=Ht(De(e)),a.decayScalar=Ht(De(n)),a.momentumScalar=Ht(De(r)),a.oneMinusDecay=Ht(De(1-n)),a.centered=o,null===i&&(i=Ut.get("EPSILON")),a.epsilonScalar=Ht(De(i)),a}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=function(n){var i=Ut.engine.registeredVariables[n];null==r.accumulatedMeanSquares[n]&&Gt(function(){e.accumulatedMeanSquares[n]=qe(i).variable(!1)}),null==r.accumulatedMeanGrads[n]&&r.centered&&Gt(function(){e.accumulatedMeanGrads[n]=qe(i).variable(!1)}),null==r.accumulatedMoments[n]&&Gt(function(){e.accumulatedMoments[n]=qe(i).variable(!1)});var o=r.accumulatedMeanSquares[n],a=r.accumulatedMeanGrads[n],s=r.accumulatedMoments[n],u=t[n];Gt(function(){var t=e.decayScalar.mul(o).add(e.oneMinusDecay.mul(u.square()));if(e.centered){var r=e.decayScalar.mul(a).add(e.oneMinusDecay.mul(u)),l=e.momentumScalar.mul(s).add(e.c.mul(u).div(t.sub(r.square().add(e.epsilonScalar)).sqrt()));e.accumulatedMeanSquares[n].assign(t),e.accumulatedMeanGrads[n].assign(r),e.accumulatedMoments[n].assign(l);var c=i.sub(l);i.assign(c)}else{var p=e.decayScalar.mul(o).add(e.oneMinusDecay.mul(u.square()));l=e.momentumScalar.mul(s).add(e.c.mul(u).div(p.add(e.epsilonScalar).sqrt())),e.accumulatedMeanSquares[n].assign(p),e.accumulatedMoments[n].assign(l),c=i.sub(l),i.assign(c)}})},r=this;for(var i in t)n(i)},e.prototype.dispose=function(){var t=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(e){return t.accumulatedMeanSquares[e].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(e){return t.accumulatedMeanGrads[e].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(e){return t.accumulatedMoments[e].dispose()})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSPropOptimizer",e}(jc);Fc(Yc);var Jc=function(){function t(){}return t.sgd=function(t){return new $c(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Xc(t,e,n)},t.rmsprop=function(t,e,n,r,i){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===i&&(i=!1),new Yc(t,e,n,r,i)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new Hc(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new qc(t,e,n)},t.adamax=function(t,e,n,r,i){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===i&&(i=0),new Kc(t,e,n,r,i)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new Gc(t,e)},t}(),Zc={sgd:Jc.sgd,momentum:Jc.momentum,adadelta:Jc.adadelta,adagrad:Jc.adagrad,rmsprop:Jc.rmsprop,adamax:Jc.adamax,adam:Jc.adam},Qc=Mt.setBackend,tp=Mt.getBackend,ep=Mt.disposeVariables,np=Mt.memory;!function(t){st=t}(Ml);var rp=function(t,e){return(rp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function ip(t,e){function n(){this.constructor=t}rp(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var op,ap=function(){return(ap=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function sp(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})}function up(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=e.call(t,a)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function lp(){return null==op&&(op=Ut.get("EPSILON")),op}var cp=0;function pp(){return cp++}var hp={};function fp(t){return void 0===t&&(t=""),t in hp||(hp[t]=0),hp[t]+=1,t+hp[t].toString()}var dp={},mp="float32";function gp(t,e){return void 0===e&&(e=mp),null==dp[e]&&(dp[e]={}),null==dp[e][t]&&(dp[e][t]=De(t,e),Ht(dp[e][t])),dp[e][t]}var yp=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return ip(e,t),e}(Error),vp=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return ip(e,t),e}(Error),bp=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return ip(e,t),e}(Error),wp=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return ip(e,t),e}(Error),xp=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return ip(e,t),e}(Error);!function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}ip(e,t)}(Error);function Np(t,e){if(Array.isArray(t)){for(var n=[],r=0;r<e;r++)n=n.concat(t);return n}return(n=new Array(e)).fill(t),n}function Sp(t,e){if(!t)throw new xp(e)}function Cp(t,e){for(var n=0,r=0,i=t;r<i.length;r++)i[r]===e&&n++;return n}function Ep(t){return 1===t.length?t[0]:t}function Ip(t){return Array.isArray(t)?t:[t]}function kp(t){var e=t.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==e[0]?e:"private"+e}function Ap(t){return t.length<=1?t:-1===t.indexOf("_")?t:t.replace(/[_]+(\w|$)/g,function(t,e){return e.toUpperCase()})}var Tp={};function Rp(t){if(null===t||void 0===t)return null;var e={};return e.className=t.getClassName(),e.config=t.getConfig(),e}function Dp(t,e,n,r,i){var o,a,s;if(void 0===e&&(e={}),void 0===n&&(n={}),void 0===r&&(r="object"),void 0===i&&(i=!1),"string"==typeof t){var u=t,l=void 0;if(u in n)l=n[u];else if(u in Tp)l=Tp[u];else if(null==(l=e[u]))throw new bp("Unknown "+r+": "+t+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");return l}var c=t;if(null==c.className||null==c.config)throw new bp(r+": Improper config format: "+JSON.stringify(c)+".\n'className' and 'config' must set.");var p=c.className,h=void 0,f=void 0;if(p in n?(h=(o=n.get(p))[0],f=o[1]):p in Tp?(h=(a=Tp.className)[0],f=a[1]):p in e&&(h=(s=e[p])[0],f=s[1]),null==h)throw new bp("Unknown "+r+": "+p+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");if(null!=f){for(var d={},m=0,g=Object.keys(Tp);m<g.length;m++)d[N=g[m]]=Tp[N];for(var y=0,v=Object.keys(n);y<v.length;y++)d[N=v[y]]=n[N];c.config.customObjects=d;for(var b=ap({},Tp),w=0,x=Object.keys(n);w<x.length;w++){var N=x[w];Tp[N]=n[N]}!function t(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach(function(e){return t(e)});else for(var n=0,r=Object.keys(e);n<r.length;n++){var i=r[n],o=e[i];null!=o&&"object"==typeof o&&(Array.isArray(o)||"ndarray"!==o.type||"number"!=typeof o.value?t(o):e[i]=o.value)}}(c.config);var S=f(h,c.config,n,i);return Tp=ap({},b),S}b=ap({},Tp);for(var C=0,E=Object.keys(n);C<E.length;C++)N=E[C],Tp[N]=n[N];return S=new h(c.config),Tp=ap({},b),S}function Op(t,e){return-1*function(t,e){return t<e?-1:t>e?1:0}(t,e)}function _p(t){if(null==t)return t;for(var e=[],n=0,r=t;n<r.length;n++){var i=r[n];-1===e.indexOf(i)&&e.push(i)}return e}function Mp(t){if(null==t)throw new bp("Invalid value in obj: "+JSON.stringify(t));for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function Lp(t,e,n){if(null!=n&&t.indexOf(n)<0)throw new bp(n+" is not a valid "+e+".  Valid values are "+t+" or null/undefined.")}function Fp(t,e,n,r){return void 0===n&&(n=0),void 0===r&&(r=1/0),Sp(n>=0),Sp(r>=n),Array.isArray(t)&&t.length>=n&&t.length<=r&&t.every(function(t){return typeof t===e})}function zp(t,e){Array.isArray(t)?(X.assert(t.length>0,function(){return e+" is unexpectedly an empty array."}),t.forEach(function(t,n){return zp(t,"element "+(n+1)+" of "+e)})):X.assert(Number.isInteger(t)&&t>0,function(){return"Expected "+e+" to be a positive integer, but got "+function t(e){return null===e?"null":Array.isArray(e)?"["+e.map(function(e){return t(e)}).join(",")+"]":"string"==typeof e?'"'+e+'"':""+e}(t)+"."})}function Pp(t,e){return Gt(function(){return Wa(Qs(ku(t,t),e,!0))})}var Bp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.getConfig=function(){return{}},e}(zc.Serializable),Up=function(t){function e(e){var n=t.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return ip(e,t),e.prototype.apply=function(t){var e=this;return Gt(function(){var n=Pp(t,e.axis),r=Na(n,0,e.maxValue);return Iu(t,yu(r,fu(gp(lp()),n)))})},e.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},e.className="MaxNorm",e}(Bp);zc.registerClass(Up);var Wp=function(t){function e(e){var n=t.call(this)||this;return n.defaultAxis=0,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return ip(e,t),e.prototype.apply=function(t){var e=this;return Gt(function(){return yu(t,fu(gp(lp()),Pp(t,e.axis)))})},e.prototype.getConfig=function(){return{axis:this.axis}},e.className="UnitNorm",e}(Bp);zc.registerClass(Wp);var Vp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return ju(t)},e.className="NonNeg",e}(Bp);zc.registerClass(Vp);var jp=function(t){function e(e){var n=t.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=e.minValue?e.minValue:n.defaultMinValue,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.rate=null!=e.rate?e.rate:n.defaultRate,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return ip(e,t),e.prototype.apply=function(t){var e=this;return Gt(function(){var n=Pp(t,e.axis),r=fu(Iu(gp(e.rate),Na(n,e.minValue,e.maxValue)),Iu(gp(1-e.rate),n));return Iu(t,yu(r,fu(gp(lp()),n)))})},e.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},e.className="MinMaxNorm",e}(Bp);zc.registerClass(jp);var qp={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Gp(t){return Rp(t)}function Hp(t,e){return void 0===e&&(e={}),Dp(t,zc.SerializationMap.getMap().classNameMap,e,"constraint")}function Kp(t){return null==t?null:"string"==typeof t?Hp({className:t in qp?qp[t]:t,config:{}}):t instanceof Bp?t:Hp(t)}var $p=Object.freeze({maxNorm:function(t){return new Up(t)},unitNorm:function(t){return new Wp(t)},nonNeg:function(){return new Vp},minMaxNorm:function(t){return new jp(t)}}),Xp=["channelsFirst","channelsLast"],Yp=["valid","same","causal"],Jp=["max","avg"],Zp=["sum","mul","concat","ave"],Qp=new Map;function th(t){Lp(Xp,"DataFormat",t)}function eh(t){Lp(Yp,"PaddingMode",t)}var nh=[],rh="/";function ih(t,e){nh.push(t);try{var n=e();return nh.pop(),n}catch(t){throw nh.pop(),t}}function oh(t){if(!uh(t))throw new Error("Not a valid tensor name: '"+t+"'");return(0===nh.length?"":nh.join(rh)+rh)+t}function ah(t){if(!uh(t))throw new Error("Not a valid tensor name: '"+t+"'");Qp.has(t)||Qp.set(t,0);var e=Qp.get(t);if(Qp.set(t,Qp.get(t)+1),e>0){var n=t+"_"+e;return Qp.set(n,1),n}return t}var sh=new RegExp(/^[A-Za-z][-A-Za-z0-9\._\/]*$/);function uh(t){return!!t.match(sh)}function lh(t){return t===parseInt(t.toString(),10)}function ch(t,e,n){null==e&&(e=0),null==n&&(n=t.length);for(var r=1,i=e;i<n;++i)r*=t[i];return r}function ph(t){return Oe(t=Array.isArray(t)?new Float32Array(t):t)}function hh(t){return Js(ph(t)).dataSync()[0]}function fh(t){return Xs(ph(t)).dataSync()[0]}function dh(t,e){if(e<t)throw new bp("end ("+e+") < begin ("+t+") is forbidden.");for(var n=[],r=t;r<e;++r)n.push(r);return n}function mh(t,e){return t.asType(e)}function gh(t,e){void 0===e&&(e=-1);var n=t.shape.slice();return e<0&&(e=n.length+e+1),n.splice(e,0,1),t.reshape(n)}function yh(t,e,n){return Gt(function(){switch(t.rank){case 1:return Bs(t,e,n);case 2:return Us(t,[e,0],[n,t.shape[1]]);case 3:return Ws(t,[e,0,0],[n,t.shape[1],t.shape[2]]);case 4:return Vs(t,[e,0,0,0],[n,t.shape[1],t.shape[2],t.shape[3]]);default:throw new bp("sliceAlongFirstAxis() received an unsupported tensor rank: "+t.rank)}})}function vh(t,e,n){return Gt(function(){switch(t.rank){case 1:return Bs(t,e,n);case 2:return Us(t,[0,e],[t.shape[0],n]);case 3:return Ws(t,[0,0,e],[t.shape[0],t.shape[1],n]);case 4:return Vs(t,[0,0,0,e],[t.shape[0],t.shape[1],t.shape[2],n]);default:throw new bp("sliceAlongLastAxis() received an unsupported tensor rank: "+t.rank)}})}function bh(t,e,n,r){return Gt(function(){switch(t.rank){case 1:return Bs(t,e,n);case 2:switch(r){case 1:return yh(t,e,n);case 2:return vh(t,e,n);default:throw new bp("The axis is not within the rank of the tensor "+r)}case 3:switch(r){case 1:return yh(t,e,n);case 2:return Ws(t,[0,e,0],[t.shape[0],n,t.shape[2]]);case 3:return vh(t,e,n);default:throw new bp("The axis is not within the rank of the tensor "+r)}case 4:switch(r){case 1:return yh(t,e,n);case 2:return Vs(t,[0,e,0,0],[t.shape[0],n,t.shape[2],t.shape[3]]);case 3:return Vs(t,[0,0,e,0],[t.shape[0],t.shape[1],n,t.shape[3]]);case 4:return vh(t,e,n);default:throw new bp("The axis is not within the rank of the tensor "+r)}default:throw new bp("sliceAlongLastAxis() received an unsupported tensor rank: "+t.rank)}})}function wh(t,e){var n;return void 0===e&&(e=-1),e<0&&(e=0!==(n=t[0].rank)?n:0),e===t[0].rank&&(e=-1),No(t,e)}function xh(t,e){switch(t.rank){case 1:return So([t,e]);case 2:return Co([t,e],0);case 3:return Eo([t,e],0);case 4:return Io([t,e],0);default:throw new bp("concatAlongFirstAxis() received an unsupported tensor rank: "+t.rank)}}function Nh(t,e){if(Array.isArray(e)||(e=[e]),t.rank!==e.length)throw new bp("The length of input n ("+e.length+") does not match the number of dimensions in input x ("+t.rank+")");return sa(t,e)}function Sh(t,e,n,r,i){return void 0===e&&(e=0),void 0===n&&(n=1),ea(t,e,n,r,i)}function Ch(t,e){if(t.rank<2||e.rank<2)throw new wp("dot requires both inputs to be rank >= 2 but got x shape = "+t.shape+" and y shape = "+e.shape);if(e.rank>=3&&(r=t.shape.slice(-1)[0])!==(a=e.shape.slice(-2)[0]))throw new wp("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+t.shape+" and  y shape = "+e.shape);if(2===t.rank&&2===e.rank)return Es(t,e);var n=t.shape.slice(),r=n.pop();t=t.reshape([-1,r]);var i=e.shape.slice(),o=i.pop(),a=i.pop(),s=i.concat([o]),u=Array.from({length:e.rank},function(t,n){return 0===n?e.rank-2:n<=e.rank-2?n-1:n});e=e.transpose(u).reshape([a,-1]);var l=n.concat(s);return Es(t,e).reshape(l)}function Eh(t,e,n){return Gt(function(){return e=Array.isArray(e)?Oe(e,"int32"):e.toInt(),Yu(t,e,n)})}function Ih(t){return ku(t,t)}function kh(t,e,n){return Gt(function(){if(null==n&&(n="channelsLast"),th(n),1!==e.rank&&e.rank!==t.rank)throw new bp("Unexpected bias dimensions: "+e.rank+"; expected it to be 1 or "+t.rank);var r,i=e.shape;if(5===t.rank)"channelsFirst"===n?r=1===i.length?t.add(e.reshape([1,i[0],1,1,1])):t.add(e.reshape([1,i[3],i[0],i[1],i[2]])):"channelsLast"===n&&(r=1===i.length?t.add(e.reshape([1,1,1,1,i[0]])):t.add(e.reshape([1].concat(i))));else if(4===t.rank)"channelsFirst"===n?r=1===i.length?t.add(e.reshape([1,i[0],1,1])):t.add(e.reshape([1,i[2],i[0],i[1]])):"channelsLast"===n&&(r=1===i.length?t.add(e.reshape([1,1,1,i[0]])):t.add(e.reshape([1].concat(i))));else if(3===t.rank)"channelsFirst"===n?r=1===i.length?t.add(e.reshape([1,i[0],1])):t.add(e.reshape([1,i[1],i[0]])):"channelsLast"===n&&(r=1===i.length?t.add(e.reshape([1,1,i[0]])):t.add(e.reshape([1].concat(i))));else{if(!(t.rank<3))throw new bp("Unsupported input rank by biasAdd: "+t.rank);r=t.add(e)}return r})}function Ah(t,e,n,r){return Gt(function(){if(null!=n&&!X.arraysEqual(t.shape,n))throw new wp("Non-default noise shape is not implemented yet: "+JSON.stringify(n));if(null!=r)throw new wp("seed is not implemented for dropout yet.");var i=ja(fu(Oa(e),na(t.shape,0,1,"float32")));return i=Iu(yu(gp(1),Ou(gp(1),e)),i),Iu(t,i)})}function Th(t,e,n){return void 0===n&&(n=!1),n?t():e()}var Rh=["fanIn","fanOut","fanAvg"],Dh=["normal","uniform"];var Oh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.fromConfigUsesCustomObjects=function(){return!1},e.prototype.getConfig=function(){return{}},e}(zc.Serializable),_h=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t,e){return Be(t,e)},e.className="Zeros",e}(Oh);zc.registerClass(_h);var Mh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t,e){return Pe(t,e)},e.className="Ones",e}(Oh);zc.registerClass(Mh);var Lh=function(t){function e(e){var n=t.call(this)||this;if("object"!=typeof e)throw new bp("Expected argument of type ConstantConfig but got "+e);if(void 0===e.value)throw new bp("config must have value set but got "+e);return n.value=e.value,n}return ip(e,t),e.prototype.apply=function(t,e){var n=this;return Gt(function(){return Iu(De(n.value),Pe(t,e))})},e.prototype.getConfig=function(){return{value:this.value}},e.className="Constant",e}(Oh);zc.registerClass(Lh);var Fh=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=e.minval||n.DEFAULT_MINVAL,n.maxval=e.maxval||n.DEFAULT_MAXVAL,n.seed=e.seed,n}return ip(e,t),e.prototype.apply=function(t,e){return na(t,this.minval,this.maxval,e)},e.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},e.className="RandomUniform",e}(Oh);zc.registerClass(Fh);var zh=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return ip(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new wp("randomNormal does not support dType "+e+".");return Sh(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="RandomNormal",e}(Oh);zc.registerClass(zh);var Ph=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return ip(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new wp("truncatedNormal does not support dType "+e+".");return ua(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="TruncatedNormal",e}(Oh);zc.registerClass(Ph);var Bh=function(t){function e(e){var n=t.call(this)||this;return n.gain=null!=e.gain?De(e.gain):gp(1),n}return ip(e,t),e.prototype.apply=function(t,e){var n=this;return Gt(function(){if(2!==t.length||t[0]!==t[1])throw new bp("Identity matrix initializer can only be used for 2D square matrices.");return Iu(n.gain,Ho(t[0]))})},e.prototype.getConfig=function(){return{gain:this.gain.dataSync()[0]}},e.className="Identity",e}(Oh);zc.registerClass(Bh);var Uh=function(t){function e(e){var n=t.call(this)||this;if(e.scale<0)throw new bp("scale must be a positive float. Got: "+e.scale);return n.scale=null==e.scale?1:e.scale,n.mode=e.mode,function(t){Lp(Rh,"FanMode",t)}(n.mode),n.distribution=e.distribution,function(t){Lp(Dh,"Distribution",t)}(n.distribution),n.seed=e.seed,n}return ip(e,t),e.prototype.apply=function(t,e){var n=function(t,e){var n,r;if(void 0===e&&(e="channelsLast"),th(e),2===t.length)n=t[0],r=t[1];else if(-1!==[3,4,5].indexOf(t.length))if("channelsFirst"===e){var i=ch(t,2);n=t[1]*i,r=t[0]*i}else"channelsLast"===e&&(i=ch(t,0,t.length-2),n=t[t.length-2]*i,r=t[t.length-1]*i);else{var o=ch(t);n=Math.sqrt(o),r=Math.sqrt(o)}return[n,r]}(t),r=n[0],i=n[1],o=this.scale;if("fanIn"===this.mode?o/=Math.max(1,r):"fanOut"===this.mode?o/=Math.max(1,i):o/=Math.max(1,(r+i)/2),"normal"===this.distribution){var a=Math.sqrt(o);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new wp(this.getClassName()+" does not support dType "+e+".");return ua(t,0,a,e,this.seed)}var s=Math.sqrt(3*o);return na(t,-s,s,e)},e.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},e.className="VarianceScaling",e}(Oh);zc.registerClass(Uh);var Wh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return ip(e,t),e.prototype.getClassName=function(){return Uh.className},e.className="GlorotUniform",e}(Uh);zc.registerClass(Wh);var Vh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return ip(e,t),e.prototype.getClassName=function(){return Uh.className},e.className="GlorotNormal",e}(Uh);zc.registerClass(Vh);var jh=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return ip(e,t),e.prototype.getClassName=function(){return Uh.className},e.className="HeNormal",e}(Uh);zc.registerClass(jh);var qh=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return ip(e,t),e.prototype.getClassName=function(){return Uh.className},e.className="HeUniform",e}(Uh);zc.registerClass(qh);var Gh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return ip(e,t),e.prototype.getClassName=function(){return Uh.className},e.className="LeCunNormal",e}(Uh);zc.registerClass(Gh);var Hh=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return ip(e,t),e.prototype.getClassName=function(){return Uh.className},e.className="LeCunNormal",e}(Uh);zc.registerClass(Hh);var Kh=function(t){function e(e){var n=t.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==e.gain?n.DEFAULT_GAIN:e.gain,n.seed=e.seed,null!=n.seed)throw new wp("Random seed is not implemented for Orthogonal Initializer yet.");return n}return ip(e,t),e.prototype.apply=function(t,e){var n=this;return Gt(function(){if(2!==t.length)throw new wp("The Orthogonal Initializer does not support non-2D shapes yet.");t[0]*t[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+t[0]*t[1]+") elements: Slowness may result.");var e=Sh(t[0]>t[1]?[t[1],t[0]]:t,0,1,"float32"),r=Cl.gramSchmidt(e);return t[0]>t[1]&&(r=r.transpose()),Iu(gp(n.gain),r)})},e.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},e.className="Orthogonal",e}(Oh);zc.registerClass(Kh);var $h={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Xh(t,e){return void 0===e&&(e={}),Dp(t,zc.SerializationMap.getMap().classNameMap,e,"initializer")}function Yh(t){return Rp(t)}function Jh(t){if("string"==typeof t){var e=t in $h?$h[t]:t;if("GlorotNormal"===e)return new Vh;if("GlorotUniform"===e)return new Wh;if("HeNormal"===e)return new jh;if("HeUniform"===e)return new qh;if("LeCunNormal"===e)return new Gh;if("LeCunUniform"===e)return new Hh;var n={};return n.className=e,n.config={},Xh(n)}return t instanceof Oh?t:Xh(t)}var Zh=Object.freeze({zeros:function(){return new _h},ones:function(){return new Mh},constant:function(t){return new Lh(t)},randomUniform:function(t){return new Fh(t)},randomNormal:function(t){return new zh(t)},truncatedNormal:function(t){return new Ph(t)},identity:function(t){return new Bh(t)},varianceScaling:function(t){return new Uh(t)},glorotUniform:function(t){return new Wh(t)},glorotNormal:function(t){return new Vh(t)},heNormal:function(t){return new jh(t)},heUniform:function(t){return new qh(t)},leCunNormal:function(t){return new Gh(t)},leCunUniform:function(t){return new Hh(t)},orthogonal:function(t){return new Kh(t)}});function Qh(t){return Array.isArray(t)&&Array.isArray(t[0])}function tf(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function ef(t){var e;if(Array.isArray(t)){if(1!==t.length)throw new bp("Expected Tensor length to be 1; got "+t.length);e=t[0]}else e=t;return e}function nf(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new bp("Expected exactly 1 Shape; got "+t.length)}return t}function rf(t){for(var e=0,n=0,r=t;n<r.length;n++){var i=r[n];0===i.shape.length?e+=1:e+=i.shape.reduce(function(t,e){return t*e})}return e}var of="Variable",af=function(){function t(t,e,n,r,i){void 0===e&&(e="float32"),void 0===n&&(n=of),void 0===r&&(r=!0),void 0===i&&(i=null),this.dtype=null==e?"float32":e,this.shape=t.shape,this.id=pp(),n=null==n?of:n,this.originalName=oh(n),this.name=ah(this.originalName),this.trainable_=r,this.constraint=i,this.val=gt(t,this.trainable_,this.name,this.dtype)}return t.prototype.read=function(){return this.assertNotDisposed(),this.val},t.prototype.write=function(t){return this.assertNotDisposed(),function(t,e){if(t.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(t.shape)+" vs. "+JSON.stringify(e.shape))}(this.val,t),this.val.id!==t.id&&(this.val.assign(t),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this},t.prototype.dispose=function(){this.assertNotDisposed(),this.val.dispose()},t.prototype.assertNotDisposed=function(){if(this.val.isDisposed)throw new Error("LayersVariable "+this.name+" is already disposed.")},Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this.trainable_=t,this.val.trainable=t},enumerable:!0,configurable:!0}),t}();function sf(t){return t.map(function(t){return t.read()})}function uf(t){t.forEach(function(t){t[0].write(t[1])})}var lf=function(t){this.dtype=t.dtype,this.shape=t.shape,null!=t.shape?this.ndim=t.shape.length:this.ndim=t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}},cf=function(t,e,n,r,i,o,a){this.dtype=t,this.shape=e,this.sourceLayer=n,this.inputs=r,this.callArgs=i,this.outputTensorIndex=a,this.id=pp(),null!=o&&(this.originalName=oh(o),this.name=ah(this.originalName)),this.rank=e.length},pf=0,hf=function(){function t(t,e){this.callArgs=e,this.id=pf++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(var n=0,r=t.inboundLayers;n<r.length;n++){var i=r[n];null!=i&&i.outboundNodes.push(this)}t.outboundLayer.inboundNodes.push(this)}return t.prototype.getConfig=function(){for(var t=[],e=0,n=this.inboundLayers;e<n.length;e++){var r=n[e];null!=r?t.push(r.name):t.push(null)}return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}},t}(),ff=0,df=function(t){function e(e){var n=t.call(this)||this;n._callHook=null,n._addedWeightNames=[],n._stateful=!1,n.id=ff++,n.activityRegularizer=null,n.inputSpec=null,n.supportsMasking=!1,n._trainableWeights=[],n._nonTrainableWeights=[],n._losses=[],n._updates=[],n._built=!1,n.inboundNodes=[],n.outboundNodes=[];var r=e.name;if(!r){var i=n.getClassName();r=kp(i)+"_"+fp(i)}if(n.name=r,n.trainable_=null==e.trainable||e.trainable,n.updatable=null==e.updatable||e.updatable,null!=e.inputShape||null!=e.batchInputShape){var o=void 0;if(null!=e.batchInputShape)o=e.batchInputShape;else if(null!=e.inputShape){var a=null;null!=e.batchSize&&(a=e.batchSize),o=[a].concat(e.inputShape)}n.batchInputShape=o;var s=e.dtype;null==s&&(s=e.inputDType),null==s&&(s="float32"),n.dtype=s}return null!=e.weights?n.initialWeights=e.weights:n.initialWeights=null,n._refCount=null,n.fastWeightInitDuringBuild=!1,n}return ip(e,t),e.nodeKey=function(t,e){return t.name+"_ib-"+e.toString()},e.prototype.getNodeAtIndex=function(t,e){if(0===this.inboundNodes.length)throw new vp("The layer has never been called and thus has no defined "+e+".");if(this.inboundNodes.length<=t)throw new bp("Asked to get "+e+" at node "+t+", but the layer has only "+this.inboundNodes.length+" inbound nodes.");return this.inboundNodes[t]},e.prototype.getInputAt=function(t){return Ep(this.getNodeAtIndex(t,"input").inputTensors)},e.prototype.getOutputAt=function(t){return Ep(this.getNodeAtIndex(t,"output").outputTensors)},Object.defineProperty(e.prototype,"input",{get:function(){if(this.inboundNodes.length>1)throw new yp("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new yp("Layer "+this.name+" is not connected, no input to return.");return Ep(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new yp("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new yp("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return Ep(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),e.prototype.calculateLosses=function(){return this.losses.map(function(t){return t()})},Object.defineProperty(e.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"built",{get:function(){return this._built},set:function(t){this._built=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this._trainableWeights.forEach(function(e){e.trainable=t}),this.trainable_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights:[]},set:function(t){this._trainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable_?this._nonTrainableWeights:this._trainableWeights.concat(this._nonTrainableWeights)},set:function(t){this._nonTrainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},e.prototype.assertInputCompatibility=function(t){if(t=Ip(t),null!=this.inputSpec&&0!==this.inputSpec.length){var e=Ip(this.inputSpec);if(t.length!==e.length)throw new bp("Layer "+this.name+" expects "+e.length+" inputs, but it received "+t.length+" input tensors. Input received: "+t);for(var n=0;n<t.length;n++){var r=t[n],i=e[n];if(null!=i){var o=r.rank;if(null!=i.ndim&&o!==i.ndim)throw new bp("Input "+n+" is incompatible with layer "+this.name+": expected ndim="+i.ndim+", found ndim="+o);if(null!=i.maxNDim&&o>i.maxNDim)throw new bp("Input "+n+" is incompatible with layer "+this.name+": expected max_ndim="+i.maxNDim+", found ndim="+o);if(null!=i.minNDim&&o<i.minNDim)throw new bp("Input "+n+" is incompatible with layer "+this.name+": expected min_ndim="+i.minNDim+", found ndim="+o+".");if(null!=i.dtype&&r.dtype!==i.dtype)throw new bp("Input "+n+" is incompatible with layer "+this.name+" : expected dtype="+i.dtype+", found dtype="+r.dtype+".");if(i.axes){var a=r.shape;for(var s in i.axes){var u=Number(s),l=i.axes[s],c=u>=0?a[u]:a[a.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new bp("Input "+n+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+a+".")}}if(null!=i.shape)for(var p=0;p<i.shape.length;++p){var h=i.shape[p],f=r.shape[p];if(null!=h&&null!=f&&h!==f)throw new bp("Input "+n+" is incompatible with layer "+this.name+": expected shape="+i.shape+", found shape=${xShape}.")}}}}},e.prototype.call=function(t,e){return t},e.prototype.invokeCallHook=function(t,e){null!=this._callHook&&this._callHook(t,e)},e.prototype.setCallHook=function(t){this._callHook=t},e.prototype.clearCallHook=function(){this._callHook=null},e.prototype.apply=function(t,e){var n=this;e=e||{},this.assertNotDisposed();for(var r=Ip(t),i=!0,o=0,a=r;o<a.length;o++)if(!(a[o]instanceof cf)){i=!1;break}for(var s=!0,u=0,l=r;u<l.length;u++)if(l[u]instanceof cf){s=!1;break}if(i===s)throw new bp("Arguments to apply() must be all SymbolicTensors or all Tensors");return ih(this.name,function(){if(!n.built){n.assertInputCompatibility(t);for(var i=[],o=0,a=Ip(t);o<a.length;o++){var u=a[o];i.push(u.shape)}n.build(Ep(i)),n.built=!0,n.initialWeights&&n.setWeights(n.initialWeights),null===n._refCount&&s&&(n._refCount=1)}if(n.assertInputCompatibility(t),s){for(var l=[],c=0,p=Ip(m=n.call(t,e));c<p.length;c++){var h=p[c];-1!==r.indexOf(h)&&(h=h.clone()),l.push(h)}if(m=Ep(l),null!=n.activityRegularizer)throw new wp("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m}var f=function(t){for(var e=[],n=0,r=t=Ip(t);n<r.length;n++){var i=r[n];e.push(i.shape)}return Ep(e)}(t),d=n.computeOutputShape(f),m=void 0,g="float32";if(n.warnOnIncompatibleInputShape(Array.isArray(t)?f[0]:f),m=null!=d&&d.length>0&&Array.isArray(d[0])?d.map(function(r,i){return new cf(g,r,n,Ip(t),e,n.name,i)}):new cf(g,d,n,Ip(t),e,n.name),n.addInboundNode(t,m,null,null,f,d,e),n._refCount++,null!=n.activityRegularizer)throw new wp("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},e.prototype.warnOnIncompatibleInputShape=function(t){if(null!=this.batchInputShape)if(t.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(t)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var e=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=t[r]&&t[r]!==n&&(e=!0)}),e&&console.warn("The shape of the input tensor ("+JSON.stringify(t)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(e.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new yp("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var t=[],e=0,n=this.inboundNodes;e<n.length;e++){var r=n[e],i=JSON.stringify(r.outputShapes);-1===t.indexOf(i)&&t.push(i)}if(1===t.length){var o=this.inboundNodes[0].outputShapes;return Array.isArray(o)&&Array.isArray(o[0])&&1===o.length?o[0]:o}throw new yp("The layer "+this.name+' has multiple inbound nodes with different output shapes. Hence the notion of "outut shape" is ill-defined for the layer.')},enumerable:!0,configurable:!0}),e.prototype.countParams=function(){if(!this.built)throw new vp("You tried to call countParams() on "+this.name+", but the layer is not built yet. Build it first by calling build(batchInputShape).");return rf(this.weights)},e.prototype.build=function(t){this.built=!0},e.prototype.getWeights=function(t){return void 0===t&&(t=!1),sf(t?this.trainableWeights:this.weights)},e.prototype.setWeights=function(t){var e=this;Gt(function(){var n=e.weights;if(n.length!==t.length)throw new bp('You called setWeights(weights) on layer "'+e.name+'" with a weight list of length '+t.length+", but the layer was expecting "+n.length+" weights. Provided weights: "+t+"...");if(0!==n.length){for(var r=[],i=sf(n),o=0;o<i.length;++o){var a=i[o],s=n[o],u=t[o];if(!X.arraysEqual(a.shape,u.shape))throw new bp("Layer weight shape "+a.shape+" not compatible with provided weight shape "+u.shape);r.push([s,u])}uf(r)}})},e.prototype.addWeight=function(t,e,n,r,i,o,a){if(-1!==this._addedWeightNames.indexOf(t))throw new bp("Duplicate weight name "+t+" for layer "+this.name);this._addedWeightNames.push(t),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=Jh("zeros"));var s=r.apply(e,n),u=new af(s,n,t,o,a);return s.dispose(),null!=i&&this.addLoss(function(){return i.apply(u.read())}),null==o&&(o=!0),o?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u},e.prototype.setFastWeightInitDuringBuild=function(t){this.fastWeightInitDuringBuild=t},e.prototype.addLoss=function(t){var e;null==t||Array.isArray(t)&&0===t.length||(t=Ip(t),void 0!==this._losses&&null!==this._losses&&(e=this.losses).push.apply(e,t))},e.prototype.computeOutputShape=function(t){return t},e.prototype.computeMask=function(t,e){var n=this;if(!this.supportsMasking){if(null!=e){if(!Array.isArray(e))throw new TypeError("Layer "+this.name+" does not support masking, but was passed an inputMask.");e.forEach(function(t){if(null!=t)throw new TypeError("Layer "+n.name+" does not support masking, but was passed an inputMask.")})}return null}return e},e.prototype.addInboundNode=function(t,e,n,r,i,o,a){void 0===a&&(a=null);var s=Ip(t);e=Ip(e),n=Ip(n),r=Ip(r),i=tf(i),o=tf(o);for(var u=[],l=[],c=[],p=0,h=s;p<h.length;p++){var f=h[p];u.push(f.sourceLayer),l.push(f.nodeIndex),c.push(f.tensorIndex)}new hf({outboundLayer:this,inboundLayers:u,nodeIndices:l,tensorIndices:c,inputTensors:s,outputTensors:e,inputMasks:n,outputMasks:r,inputShapes:i,outputShapes:o},a);for(var d=0;d<e.length;d++)e[d].sourceLayer=this,e[d].nodeIndex=this.inboundNodes.length-1,e[d].tensorIndex=d},e.prototype.getConfig=function(){var t={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(t.batchInputShape=this.batchInputShape),null!=this.dtype&&(t.dtype=this.dtype),t},e.prototype.disposeWeights=function(){return this.weights.forEach(function(t){return t.dispose()}),this.weights.length},e.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Layer '"+this.name+"' is already disposed.")},e.prototype.dispose=function(){if(!this.built)throw new Error("Cannot dispose Layer "+this.name+" because it has not been built yet.");if(null===this._refCount)throw new Error("Cannot dispose Layer "+this.name+" because it has not been used yet.");this.assertNotDisposed();var t=0;return 0==--this._refCount&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}},e}(zc.Serializable);var mf,gf=function(t){function e(e){var n=t.call(this,{dtype:e.dtype,name:null!=e.name?e.name:fp("input").toString()})||this;if(null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),n.trainable=!1,n.built=!0,n.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new bp("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");var r=e.batchInputShape;if(null==r){if(null==e.inputShape)throw new bp("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");r=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new bp("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");var i=e.dtype||"float32";n.batchInputShape=r,n.dtype=i,n.inputSpec=[{shape:r}];var o=new cf(n.dtype,n.batchInputShape,n,[],{},n.name);return o.nodeIndex=0,o.tensorIndex=0,new hf({outboundLayer:n,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[o],outputTensors:[o],inputMasks:[null],outputMasks:[null],inputShapes:[r],outputShapes:[r]}),n}return ip(e,t),e.prototype.apply=function(t,e){throw new bp("Cannot pass any input to an InputLayer's apply() method. InputLayer name: "+this.name)},e.prototype.dispose=function(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}},e.prototype.getConfig=function(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}},e.className="InputLayer",e}(df);function yf(t){if(null==t.batchShape&&null==t.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=t.batchShape&&null!=t.shape)throw new bp("Please provide either a `shape` or `batchShape` argument to Input, but not both.");var e=t.batchShape;null!=t.shape&&null==e&&(e=[null].concat(t.shape));var n=t.dtype;return null==n&&(n="float32"),new gf({batchInputShape:e,name:t.name,dtype:n,sparse:t.sparse}).inboundNodes[0].outputTensors[0]}function vf(t){return sp(this,void 0,void 0,function(){var e,n,r,i,o,a,s,u;return up(this,function(l){switch(l.label){case 0:if(null==t)return[2];for(i in e=[],n=[],r=[],t)"number"!=typeof(o=t[i])&&(a=o,e.push(a.data()),n.push(i),r.push(a));return[4,Promise.all(e)];case 1:for(s=l.sent(),u=0;u<s.length;++u)t[n[u]]=s[u][0];return Kt(r),[2]}})})}function bf(t){if(null!=t)for(var e in t){var n=t[e];"number"!=typeof n&&n.dispose()}}zc.registerClass(gf),function(t){t[t.SILENT=0]="SILENT",t[t.VERBOSE=1]="VERBOSE"}(mf||(mf={}));var wf=function(){function t(){this.validationData=null}return t.prototype.setParams=function(t){this.params=t},t.prototype.onEpochBegin=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(t){return[2]})})},t.prototype.onEpochEnd=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(t){return[2]})})},t.prototype.onBatchBegin=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(t){return[2]})})},t.prototype.onBatchEnd=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(t){return[2]})})},t.prototype.onTrainBegin=function(t){return sp(this,void 0,void 0,function(){return up(this,function(t){return[2]})})},t.prototype.onTrainEnd=function(t){return sp(this,void 0,void 0,function(){return up(this,function(t){return[2]})})},t.prototype.setModel=function(t){},t}(),xf=function(){function t(t,e){void 0===e&&(e=10),null==t&&(t=[]),this.callbacks=t,this.queueLength=e}return t.prototype.append=function(t){this.callbacks.push(t)},t.prototype.setParams=function(t){for(var e=0,n=this.callbacks;e<n.length;e++)n[e].setParams(t)},t.prototype.setModel=function(t){for(var e=0,n=this.callbacks;e<n.length;e++)n[e].setModel(t)},t.prototype.onEpochBegin=function(t,e){return sp(this,void 0,void 0,function(){var n,r;return up(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onEpochBegin(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onEpochEnd=function(t,e){return sp(this,void 0,void 0,function(){var n,r;return up(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onEpochEnd(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onBatchBegin=function(t,e){return sp(this,void 0,void 0,function(){var n,r;return up(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onBatchBegin(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onBatchEnd=function(t,e){return sp(this,void 0,void 0,function(){var n,r;return up(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onBatchEnd(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onTrainBegin=function(t){return sp(this,void 0,void 0,function(){var e,n;return up(this,function(r){switch(r.label){case 0:null==t&&(t={}),e=0,n=this.callbacks,r.label=1;case 1:return e<n.length?[4,n[e].onTrainBegin(t)]:[3,4];case 2:r.sent(),r.label=3;case 3:return e++,[3,1];case 4:return[2]}})})},t.prototype.onTrainEnd=function(t){return sp(this,void 0,void 0,function(){var e,n;return up(this,function(r){switch(r.label){case 0:null==t&&(t={}),e=0,n=this.callbacks,r.label=1;case 1:return e<n.length?[4,n[e].onTrainEnd(t)]:[3,4];case 2:r.sent(),r.label=3;case 3:return e++,[3,1];case 4:return[2]}})})},t}(),Nf=function(){function t(t){this.yieldEvery=t,this.batchCount=0,this.batchDurationsMillis=[],this.autoYieldEveryBatches=null,this.batchStartMillis=X.now()}return t.prototype.maybeYieldOnBatch=function(e){return sp(this,void 0,void 0,function(){var e,n;return up(this,function(r){switch(r.label){case 0:return"auto"!==this.yieldEvery?[3,5]:(this.batchCount++,null!=this.autoYieldEveryBatches?[3,2]:(e=X.now(),[4,zl()]));case 1:return r.sent(),this.batchCount>t.SKIP_FIRST_BATCHES&&(this.batchDurationsMillis.push(e-this.batchStartMillis),this.batchDurationsMillis.length>=t.DECISION_BATCH_COUNT&&(n=this.batchDurationsMillis.reduce(function(t,e){return t+e})/this.batchDurationsMillis.length,this.autoYieldEveryBatches=Math.round(t.THRESHOLD_MILLIS/n),this.autoYieldEveryBatches<1&&(this.autoYieldEveryBatches=1))),this.batchStartMillis=X.now(),this.lastYieldBatchCount=this.batchCount,[3,4];case 2:return this.batchCount-this.lastYieldBatchCount>=this.autoYieldEveryBatches?[4,zl()]:[3,4];case 3:r.sent(),this.lastYieldBatchCount=this.batchCount,r.label=4;case 4:return[3,7];case 5:return"batch"!==this.yieldEvery?[3,7]:[4,zl()];case 6:r.sent(),r.label=7;case 7:return[2]}})})},t.prototype.maybeYieldOnEpoch=function(){return sp(this,void 0,void 0,function(){return up(this,function(t){switch(t.label){case 0:return"epoch"!==this.yieldEvery?[3,2]:[4,zl()];case 1:t.sent(),t.label=2;case 2:return[2]}})})},t.SKIP_FIRST_BATCHES=1,t.DECISION_BATCH_COUNT=2,t.THRESHOLD_MILLIS=16,t}(),Sf=function(t){function e(e){var n=t.call(this)||this;return n.yieldEvery=e||"auto",n}return ip(e,t),e.prototype.onTrainBegin=function(t){return sp(this,void 0,void 0,function(){return up(this,function(t){return this.autoYielder=new Nf(this.yieldEvery),[2]})})},e.prototype.onEpochBegin=function(t){return sp(this,void 0,void 0,function(){return up(this,function(t){return this.seen=0,this.totals={},[2]})})},e.prototype.onBatchEnd=function(t,e){return sp(this,void 0,void 0,function(){var t,n,r,i,o=this;return up(this,function(a){switch(a.label){case 0:return[4,this.autoYielder.maybeYieldOnBatch(e)];case 1:for(i in a.sent(),null==e&&(e={}),t=null==e.size?0:e.size,this.seen+=t,n=function(n){var i=e[n];if("number"==typeof i)r.totals.hasOwnProperty(n)||(r.totals[n]=0),r.totals[n]=r.totals[n]+i*t;else{var a=void 0;n in r.totals?a=r.totals[n]:r.totals[n]=gp(0),r.totals[n]=Gt(function(){return fu(o.totals[n],Iu(i,gp(t)))}),null!=a&&a.dispose()}},r=this,e)n(i);return[2]}})})},e.prototype.onEpochEnd=function(t,e){return sp(this,void 0,void 0,function(){var t,n,r,i,o,a=this;return up(this,function(s){switch(s.label){case 0:return[4,this.autoYielder.maybeYieldOnEpoch()];case 1:if(s.sent(),null!=e)for(t=function(t){if(null==n.totals[t])return"continue";"number"==typeof n.totals[t]?e[t]=n.totals[t]/n.seen:Gt(function(){e[t]=Iu(yu(gp(1),gp(a.seen)),a.totals[t]),a.totals[t].dispose(),Ht(e[t])})},n=this,r=0,i=this.params.metrics;r<i.length;r++)o=i[r],t(o);return[2]}})})},e}(wf),Cf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.onTrainBegin=function(t){return sp(this,void 0,void 0,function(){return up(this,function(t){return this.epoch=[],this.history={},[2]})})},e.prototype.onEpochEnd=function(t,e){return sp(this,void 0,void 0,function(){var n;return up(this,function(r){for(n in null==e&&(e={}),this.epoch.push(t),e)null==this.history[n]&&(this.history[n]=[]),this.history[n].push(e[n]);return[2]})})},e.prototype.syncData=function(){return sp(this,void 0,void 0,function(){var t,e,n,r,i,o,a,s,u;return up(this,function(l){switch(l.label){case 0:for(r in t=[],e=[],n=[],this.history)for(i=this.history[r],o=0;o<i.length;++o)"number"!=typeof i[o]&&(a=i[o],t.push(a.data()),e.push(r),n.push(o));return[4,Promise.all(t)];case 1:for(s=l.sent(),u=0;u<s.length;++u)this.history[e[u]][n[u]].dispose(),this.history[e[u]][n[u]]=s[u][0];return[2]}})})},e}(wf),Ef=function(t){function e(e){var n=t.call(this)||this;return n.trainBegin=e.onTrainBegin,n.trainEnd=e.onTrainEnd,n.epochBegin=e.onEpochBegin,n.epochEnd=e.onEpochEnd,n.batchBegin=e.onBatchBegin,n.batchEnd=e.onBatchEnd,n}return ip(e,t),e.prototype.onEpochBegin=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){switch(n.label){case 0:return null==this.epochBegin?[3,3]:[4,vf(e)];case 1:return n.sent(),[4,this.epochBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.onEpochEnd=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){switch(n.label){case 0:return null==this.epochEnd?[3,3]:[4,vf(e)];case 1:return n.sent(),[4,this.epochEnd(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.onBatchBegin=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){switch(n.label){case 0:return null==this.batchBegin?[3,3]:[4,vf(e)];case 1:return n.sent(),[4,this.batchBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.onBatchEnd=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){switch(n.label){case 0:return null==this.batchEnd?[3,3]:[4,vf(e)];case 1:return n.sent(),[4,this.batchEnd(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.onTrainBegin=function(t){return sp(this,void 0,void 0,function(){return up(this,function(e){switch(e.label){case 0:return null==this.trainBegin?[3,3]:[4,vf(t)];case 1:return e.sent(),[4,this.trainBegin(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})},e.prototype.onTrainEnd=function(t){return sp(this,void 0,void 0,function(){return up(this,function(e){switch(e.label){case 0:return null==this.trainEnd?[3,3]:[4,vf(t)];case 1:return e.sent(),[4,this.trainEnd(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})},e}(wf);function If(t){return null==t?null:t instanceof wf?[t]:Array.isArray(t)&&t[0]instanceof wf?t:Ip(t).map(function(t){return new Ef(t)})}var kf=function(){function t(){}return t.registerCallbackConstructor=function(e,n){X.assert(e>=0&&Number.isInteger(e),function(){return"Verbosity level is expected to be an integer >= 0, but got "+e}),t.checkForDuplicate(n),null==t.constructors[e]&&(t.constructors[e]=[]),t.constructors[e].push(n)},t.checkForDuplicate=function(e){for(var n in t.constructors)t.constructors[+n].forEach(function(t){if(t===e)throw new bp("Duplicate callback constructor.")})},t.clear=function(){t.constructors={}},t.createCallbacks=function(e){var n=[];for(var r in t.constructors){var i=+r;e>=i&&n.push.apply(n,t.constructors[i])}return n.map(function(t){return new t})},t.constructors={},t}();function Af(t,e,n,r,i,o,a,s,u,l){var c=new Cf,p=[new Sf(e)].concat(kf.createCallbacks(n));null!=t&&p.push.apply(p,t),p.push(c);var h=new xf(p);return h.setParams({epochs:r,initialEpoch:i,samples:o,steps:a,batchSize:s,verbose:n,doValidation:u,metrics:l}),{callbackList:h,history:c}}function Tf(t,e){return Gt(function(){var n=Qs(Ih(t),e,!0),r=Iu(De(lp()),je(t)),i=Wa(wu(n,r));return yu(t,i)})}function Rf(t,e){return Gt(function(){return Ys(Ih(Ou(e,t)),-1)})}function Df(t,e){return Gt(function(){return Ys(da(Ou(e,t)),-1)})}function Of(t,e){return Gt(function(){var n=Ou(t,e),r=Na(da(t),lp(),Number.MAX_VALUE),i=da(yu(n,r));return Iu(gp(100),Ys(i,-1))})}function _f(t,e){return Gt(function(){var n=gp(1),r=Na(e,lp(),Number.MAX_VALUE),i=Ta(fu(n,r)),o=Na(t,lp(),Number.MAX_VALUE),a=Ta(fu(n,o));return Ys(Ih(Ou(i,a)),-1)})}function Mf(t,e){return Gt(function(){var n=gp(0),r=gp(1),i=wu(n,Ou(r,Iu(t,e)));return Ys(Ih(i),-1)})}function Lf(t,e){return Gt(function(){var n=gp(0),r=gp(1),i=wu(n,Ou(r,Iu(t,e)));return Ys(i,-1)})}function Ff(t,e){return Gt(function(){var n=gp(0),r=gp(1),i=Qs(Iu(t,e),-1),o=Xs(Iu(Ou(r,t),e),-1);return wu(n,fu(r,Ou(o,i)))})}function zf(t,e){return Gt(function(){var n=gp(Math.log(2)),r=Ou(e,t),i=Ou(fu(r,Ua(Iu(gp(-2),r))),n);return Ys(i,-1)})}function Pf(t,e,n){return void 0===n&&(n=!1),Gt(function(){if(n)e=Ee(e);else{var r=Qs(e,e.shape.length-1,!0);e=yu(e,r)}return e=Na(e,lp(),1-lp()),Oa(Qs(Iu(t.toFloat(),Ta(e)),e.shape.length-1))})}function Bf(t,e){return Gt(function(){var n=Aa(function(t){var e=[ch(t.shape)];return t.reshape(e)}(t)).toInt(),r=(e=Na(e,lp(),1-lp())).shape;return Pf($o(n,r[r.length-1]).reshape(r),e,!1)})}function Uf(t,e){return Gt(function(){var n;return n=Na(e,lp(),1-lp()),n=Ta(yu(n,Ou(gp(1),n))),Ys(function(t,e){if(!X.arraysEqual(t.shape,e.shape))throw new bp("logits and labels must have the same shape, but got shapes "+JSON.stringify(t.shape)+" and "+JSON.stringify(e.shape));return Gt(function(){var n=e.relu(),r=e.abs().neg();return n.sub(e.mul(t)).add(r.exp().log1p())})}(t,n),-1)})}function Wf(t,e){return Gt(function(){var n=Na(t,lp(),1),r=Na(e,lp(),1);return Qs(Iu(t,Ta(yu(n,r))),-1)})}function Vf(t,e){return Gt(function(){var n=Ta(fu(gp(lp()),e));return Ys(Ou(e,Iu(t,n)),-1)})}function jf(t,e){return Gt(function(){var n=Tf(t,-1),r=Tf(e,-1),i=Iu(n,r);return Oa(Qs(i,-1))})}function qf(t){var e={meanSquaredError:Rf,meanAbsoluteError:Df,meanAbsolutePercentageError:Of,meanSquaredLogarithmicError:_f,squaredHinge:Mf,hinge:Lf,categoricalHinge:Ff,logcosh:zf,categoricalCrossentropy:Pf,sparseCategoricalCrossentropy:Bf,binaryCrossentropy:Uf,kullbackLeiblerDivergence:Wf,poisson:Vf,cosineProximity:jf};if("string"==typeof t){if(t in e)return e[t];var n="Unknown loss "+t;throw t.toLowerCase().includes("softmaxcrossentropy")&&(n="Unknown loss "+t+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new bp(n)}return t}function Gf(t,e){return Gt(function(){var n=Iu(gp(.5),je(e)),r=mh(ru(e,n),t.dtype);return Ys(eu(t,r),-1)})}function Hf(t,e){return Gt(function(){return mh(eu(Hs(t,-1),Hs(e,-1)),"float32")})}function Kf(t,e){return Gt(function(){var n=gp(1);return Mu(t.equal(n),e.equal(n)).sum().cast("float32")})}function $f(t,e){return Gt(function(){var n=gp(0),r=Kf(t,e),i=function(t,e){return Gt(function(){var n=gp(1),r=gp(0);return Mu(t.equal(r),e.equal(n)).sum().cast("float32")})}(t,e),o=r.add(i);return Pu(ru(o,n),r.div(o),n).cast("float32")})}function Xf(t,e){return Gt(function(){var n=gp(0),r=Kf(t,e),i=function(t,e){return Gt(function(){var n=gp(1),r=gp(0);return Mu(t.equal(n),e.equal(r)).sum().cast("float32")})}(t,e),o=r.add(i);return Pu(ru(o,n),r.div(o),n).cast("float32")})}function Yf(t,e){return Uf(t,e)}function Jf(t,e){return t.rank===e.rank&&(t=t.squeeze([t.rank-1])),(e=e.argMax(-1)).dtype!==t.dtype&&(e=e.asType(t.dtype)),eu(t,e).asType("float32")}var Zf=Rf,Qf=Rf,td=Df,ed=Df,nd=Of,rd=Of,id=Pf,od=jf,ad=Bf;function sd(t,e,n,r){void 0===r&&(r=console.log);var i,o=function(t){var e=!0,n=[],r=[];for(var i in t.nodesByDepth)n.push(t.nodesByDepth[i]);for(var o=0,a=n;o<a.length;o++){var s=a[o];if(s.length>1||1===s.length&&s[0].inboundLayers.length>1){e=!1;break}r.push.apply(r,s)}if(e)for(var u=0,l=t.layers;u<l.length;u++){for(var c=!1,p=0,h=l[u].inboundNodes;p<h.length;p++){var f=h[p];if(-1!==r.indexOf(f)){if(c){e=!1;break}c=!0}}if(!e)break}return e}(t),a=["Layer (type)","Output shape","Param #"];if(o?(e=e||65,n=n||[.45,.85,1]):(e=e||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(function(t){return Math.floor(e*t)})),!o)for(var s in a.push("Receives inputs"),i=[],t.nodesByDepth)i.push.apply(i,t.nodesByDepth[s]);r("_".repeat(e)),ud(a,n,r),r("=".repeat(e));for(var u=t.layers,l=0;l<u.length;++l)o?ld(u[l],n,r):cd(u[l],n,i,r),r((l===u.length-1?"=":"_").repeat(e));t.checkTrainableWeightsConsistency();var c=function(t){return null!=t.collectedTrainableWeights?rf(t.collectedTrainableWeights):rf(t.trainableWeights)}(t),p=rf(t.nonTrainableWeights);r("Total params: "+(c+p)),r("Trainable params: "+c),r("Non-trainable params: "+p),r("_".repeat(e))}function ud(t,e,n){void 0===n&&(n=console.log);for(var r="",i=0;i<t.length;++i)i>0&&(r=r.slice(0,r.length-1)+" "),r=(r+=t[i]).slice(0,e[i]),r+=" ".repeat(e[i]-r.length);n(r)}function ld(t,e,n){var r;try{r=JSON.stringify(t.outputShape)}catch(t){r="multiple"}ud([t.name+" ("+t.getClassName()+")",r,t.countParams().toString()],e,n)}function cd(t,e,n,r){var i;try{i=JSON.stringify(t.outputShape)}catch(t){i="multiple"}for(var o=[],a=0,s=t.inboundNodes;a<s.length;a++){var u=s[a];if(!(null!=n&&n.length>0&&-1===n.indexOf(u)))for(var l=0;l<u.inboundLayers.length;++l){var c=u.inboundLayers[l].name,p=u.nodeIndices[l],h=u.tensorIndices[l];o.push(c+"["+p+"]["+h+"]")}}var f=t.name,d=t.getClassName(),m=0===o.length?"":o[0];for(ud([f+" ("+d+")",i,t.countParams().toString(),m],e,r),l=1;l<o.length;++l)ud(["","","",o[l]],e,r)}function pd(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),Dp(t,zc.SerializationMap.getMap().classNameMap,e,"layer",n)}function hd(t,e,n){return("inboundNodes"===t||"outputLayers"===t||"inputLayers"===t)&&0===e&&"string"==typeof n}function fd(t,e){if(null===t)return null;if("string"==typeof t)return Ap(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){for(var n=[],r=t.length,i=0;i<r;++i){var o=t[i];hd(e,i,o)?n.push(o):n.push(fd(o,e))}return n}for(var a={},s=0,u=Object.keys(t);s<u.length;s++){var l=u[s],c=t[l];if("name"===l&&"string"==typeof c)a[l]=c;else{var p=Ap(l);a[p]=fd(c,p)}}return a}var dd=function(){function t(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof t)for(var n in e.id2Value)this.id2Value[n]=e.id2Value[n],n in e.id2Mask&&(this.id2Mask[n]=e.id2Mask[n]);else{if(null==e)return;for(var r=0,i=e;r<i.length;r++){var o=i[r];this.add(o.key,o.value)}}}return t.prototype.add=function(t,e,n){if(null!=this.id2Value[t.id])throw new bp("Duplicate key: name="+t.name+", id="+t.id);return this.id2Value[t.id]=function(t,e){if(null==t.dtype||t.dtype===e.dtype)return e;try{return Wo(e,t.dtype)}catch(n){throw new bp("The dtype of the feed ("+e.dtype+") can not be cast to the dtype of the key '"+t.name+"' ("+t.dtype+").")}}(t,e),this.name2Id[t.name]=t.id,null!=n&&(this.id2Mask[t.id]=n),this},t.prototype.addFeed=function(t){this.add(t.key,t.value)},t.prototype.hasKey=function(t){return null!=this.id2Value[t.id]},t.prototype.names=function(){return Object.keys(this.name2Id)},t.prototype.getValue=function(t){if(t instanceof cf){if(null==this.id2Value[t.id])throw new bp("Nonexistent key: "+t.name);return this.id2Value[t.id]}var e=this.name2Id[t];if(null==e)throw new bp("Feed dict has no SymbolicTensor name: "+t);return this.id2Value[e]},t.prototype.getMask=function(t){if(t instanceof cf){if(null==this.id2Value[t.id])throw new bp("Nonexistent key: "+t.name);return this.id2Mask[t.id]}var e=this.name2Id[t];if(null==e)throw new bp("Feed dict has no SymbolicTensor name: "+t);return this.id2Mask[e]},t.prototype.disposeMasks=function(){null!=this.id2Mask&&Kt(this.id2Mask)},t}(),md={},gd={};function yd(t,e,n,r){for(var i=null!=n&&n.training,o=Array.isArray(t),a=o?t:[t],s=a.map(function(t){return t.name}),u=[],l=e.names(),c=0,p=s;c<p.length;c++){var h=p[c];-1!==l.indexOf(h)?u.push(e.getValue(h)):u.push(null)}null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);var f,d,m=s.join(",")+"|"+e.names().join(",");if(null==md[m]){var g=function(t,e){X.assert(null!=t&&t.length>0,function(){return"Expected at least one fetch, got none"});var n=[],r={};if(1===t.length){var i=vd(t[0],e);n=i.sorted,r=i.recipientMap}else for(var o=new Set,a=0,s=t;a<s.length;a++){for(var u=vd(s[a],e),l=u.sorted,c=u.recipientMap,p=0,h=l;p<h.length;p++){var f=h[p];o.has(f.name)||(n.push(f),o.add(f.name))}var d=function(t){null==r[t]&&(r[t]=new Set),c[t].forEach(function(e){return r[t].add(e)})};for(var m in c)d(m)}return{sorted:n,recipientCounts:function(t){var e={};for(var n in t)e[n]=t[n].size;return e}(r)}}(a,e);f=g.sorted,d=g.recipientCounts,md[m]=f,gd[m]=d}f=md[m],d={},i||Object.assign(d,gd[m]);for(var y=new dd(e),v=0;v<f.length;++v){if(null!=r){var b=np().numTensors;b>r.maxNumTensors&&(r.maxNumTensors=b),b<r.minNumTensors&&(r.minNumTensors=b)}var w=f[v],x=w.sourceLayer;if(!(x instanceof gf)){for(var N=[],S=[],C=[],E=!1,I=0,k=w.inputs;I<k.length;I++){var A=k[I],T=y.getValue(A),R=y.getMask(A);N.push(T),S.push(R),null!=R&&(E=!0),i||(d[A.name]--,0!==d[A.name]||e.hasKey(A)||-1!==s.indexOf(A.name)||T.isDisposed||C.push(T))}E&&((n=n||{}).mask=S[0]);var D=Ip(x.apply(N,n)),O=null;x.supportsMasking&&(O=x.computeMask(N,S));for(var _=bd(w),M=Array.isArray(_)?_:[_],L=0;L<M.length;++L){y.hasKey(M[L])||y.add(M[L],D[L],Array.isArray(O)?O[0]:O);var F=s.indexOf(M[L].name);-1!==F&&(u[F]=D[L])}i||Kt(C)}}return y.disposeMasks(),o?u:u[0]}function vd(t,e){for(var n=new Set,r=[],i={},o=0,a=e.names();o<a.length;o++){var s=a[o];n.add(s)}var u=[],l=[];for(u.push(t);u.length>0;){var c=u[u.length-1];if(n.has(c.name))u.pop();else{var p=l[l.length-1]===u.length-1;if(0===c.inputs.length||p)u.pop(),r.push(c),n.add(c.name),p&&l.pop();else{l.push(u.length-1);for(var h=0,f=c.inputs;h<f.length;h++){var d=f[h];null==i[d.name]&&(i[d.name]=new Set),i[d.name].add(c.name),n.has(d.name)||u.push(d)}}}}return{sorted:r,recipientMap:i}}function bd(t){var e;if(1===t.sourceLayer.inboundNodes.length)e=t.sourceLayer.output;else{for(var n=null,r=0;r<t.sourceLayer.inboundNodes.length;++r)for(var i=0,o=t.sourceLayer.inboundNodes[r].outputTensors;i<o.length;i++)if(o[i].id===t.id){n=r;break}e=t.sourceLayer.getOutputAt(n)}return e}var wd=32;function xd(t,e){var n,r,i=e;n=i.xs,r=i.ys,X.assert(null!=n&&null!=r,function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor.  The provided Dataset instead generates "+e});var o=Nd("input",t.inputNames,n),a=Nd("output",t.outputNames,r),s=o[0].shape[0];X.assert(o.length===t.inputs.length,function(){return"LayersModel has "+t.inputs.length+" inputs, but the dataset provides "+o.length+" inputs.  (Expected input keys: "+JSON.stringify(t.inputNames)+")"}),X.assert(a.length===t.outputs.length,function(){return"LayersModel has "+t.outputs.length+" outputs, but the dataset provides "+a.length+" outputs.  (Expected output keys: "+JSON.stringify(t.outputNames)+")"});var u=function(e){X.assert(o[e].shape[0]===s,function(){return"Batch size mismatch: input "+t.inputNames[e]+" has "+o[e].shape[0]+"; expected  "+s+" based on input "+t.inputNames[0]+"."})};for(var l in o)u(l);var c=function(e){X.assert(a[e].shape[0]===s,function(){return"Batch size mismatch: output "+t.outputNames[e]+" has "+a[e].shape[0]+"; expected  "+s+" based on input "+t.inputNames[0]+"."})};for(var p in a)c(p);return o.concat(a)}function Nd(t,e,n){if(n instanceof lt)return[n];if(Array.isArray(n))return X.assert(n.length===e.length,function(){return"Received an array of "+n.length+" Tensors, but expected "+e.length+" to match the "+t+" keys "+e+"."}),n;for(var r=[],i=0,o=e;i<o.length;i++){var a=o[i];if(null==n[a])throw new bp("The feature data generated by the dataset lacks the required "+t+" key '"+a+"'.");r.push(n[a])}return r}function Sd(t,e,n){return sp(this,void 0,void 0,function(){var r,i,o,a,s,u,l,c,p,h,f,d,m,g,y,v,b,w,x,N,S,C,E,I,k,A,T;return up(this,function(R){switch(R.label){case 0:if(r=null!=n.batchesPerEpoch,X.assert(null!=t.optimizer,function(){return"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."}),X.assert(null!=n,function(){return"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."}),X.assert(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive integer, but got "+n.epochs}),X.assert(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+n.batchesPerEpoch}),X.assert(null==n.validationSplit,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,R.label=1;case 1:return R.trys.push([1,,22,23]),i=null!=n.validationData,o=void 0,a=void 0,i&&(Cd(n.validationData)?X.assert(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got "+n.validationBatches}):(s=function(t){if(3===t.length)throw new wp("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}(n.validationData),o=s.xs,a=s.ys)),u=t.makeTrainFunction(),l=t.getDedupedMetricsNames(),c=void 0,c=i?l.slice().concat(l.map(function(t){return"val_"+t})):l.slice(),p=If(n.callbacks),h=null==n.verbose?1:n.verbose,f=Af(p,n.yieldEvery,h,n.epochs,null,null,function(t,e){var n=null;return null!=e.batchesPerEpoch?n=e.batchesPerEpoch:Number.isFinite(t.size)&&(n=t.size),n}(e,n),null,i,c),d=f.callbackList,m=f.history,d.setModel(t),t.history=m,[4,d.onTrainBegin()];case 2:return R.sent(),t.stopTraining_=!1,g=null==n.initialEpoch?0:n.initialEpoch,[4,e.iterator()];case 3:y=R.sent(),R.label=4;case 4:return g<n.epochs?(v={},[4,d.onEpochBegin(g)]):[3,19];case 5:return R.sent(),b=0,w=0,r?[3,7]:[4,e.iterator()];case 6:y=R.sent(),R.label=7;case 7:return!r||b<n.batchesPerEpoch?[4,y.next()]:[3,17];case 8:return x=R.sent(),r&&x.done?(console.warn("You provided `batchesPerEpoch` as "+n.batchesPerEpoch+", but your dataset iterator ran out of data after "+b+" batches; interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, "+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset."),[3,17]):null==x.value?[3,11]:(N=xd(t,x.value),(S={}).batch=w,S.size=N[0].shape[0],[4,d.onBatchBegin(w,S)]);case 9:for(R.sent(),C=u(N),Kt(N),T=0;T<l.length;++T)E=l[T],I=C[T],S[E]=I,Ht(I);return[4,d.onBatchEnd(w,S)];case 10:R.sent(),bf(S),w++,b++,R.label=11;case 11:return(r?b>=n.batchesPerEpoch:x.done)?i?(k=void 0,Cd(n.validationData)?(A=Ip,[4,t.evaluateDataset(n.validationData,{batches:n.validationBatches})]):[3,13]):[3,15]:[3,16];case 12:return k=A.apply(void 0,[R.sent()]),[3,14];case 13:k=Ip(t.evaluate(o,a,{batchSize:null==n.validationBatchSize?wd:n.validationBatchSize,verbose:0})),R.label=14;case 14:for(T=0;T<t.metricsNames.length;++T)v["val_"+t.metricsNames[T]]=k[T];R.label=15;case 15:return[3,17];case 16:return t.stopTraining_?[3,17]:[3,7];case 17:return[4,d.onEpochEnd(g,v)];case 18:return R.sent(),g++,t.stopTraining_?[3,19]:[3,4];case 19:return[4,d.onTrainEnd()];case 20:return R.sent(),[4,t.history.syncData()];case 21:return R.sent(),[2,t.history];case 22:return t.isTraining=!1,[7];case 23:return[2]}})})}function Cd(t){return"function"==typeof t.iterator}function Ed(t){X.assert(t>0&&Number.isInteger(t),function(){return"batchSize is required to be a positive integer, but got "+t})}function Id(t,e,n){return null==t?[null]:Array.isArray(t)?t.map(function(t){return yh(t,e,n-e)}):yh(t,e,n-e)}function kd(t,e){return Gt(function(){return null==t?null:Array.isArray(t)?t.map(function(t){return kd(t,e)}):Eh(t,"int32"===e.dtype?e:e.toInt())})}function Ad(t,e){for(var n=[],r=0,i=null;r<t;)(i=r+e)>=t&&(i=t),n.push([r,i]),r=i;return n}function Td(t,e,n,r){return void 0===r&&(r={}),sp(this,void 0,void 0,function(){var i,o,a,s,u,l,c,p,h,f,d,m,g,y,v,b,w,x,N;return up(this,function(S){switch(S.label){case 0:if(t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,S.label=1;case 1:if(S.trys.push([1,,3,4]),Ed(c=null==r.batchSize?32:r.batchSize),p=t.standardizeUserData(e,n,!1,c),i=p[0],o=p[1],h=!1,f=void 0,null!=r.validationData&&r.validationData.length>0){if(h=!0,2!==r.validationData.length)throw 3===r.validationData.length?new wp("validationData including sample weights is not supported yet."):new bp("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+r.validationData+" is invalid.");a=r.validationData[0],s=r.validationData[1],d=t.standardizeUserData(a,s,!0,c),u=d[0],l=d[1],f=u.concat(l)}else null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1?(h=!0,m=Math.floor(i[0].shape[0]*(1-r.validationSplit)),g=i[0].shape[0],u=Id(i,m,g),i=Id(i,0,m),l=Id(o,m,g),o=Id(o,0,m),f=u.concat(l)):null!=r.validationSteps&&(h=!0);return y=i.concat(o),t.checkTrainableWeightsConsistency(),v=t.makeTrainFunction(),b=t.getDedupedMetricsNames(),w=void 0,x=void 0,h?(t.makeTestFunction(),w=t.testFunction,x=b.slice().concat(b.map(function(t){return"val_"+t}))):(w=null,f=[],x=b.slice()),N=If(r.callbacks),[4,function(t,e,n,r,i,o,a,s,u,l,c,p,h,f,d,m){return sp(this,void 0,void 0,function(){var g,y,v,b,w,x,N,S;return up(this,function(C){switch(C.label){case 0:if(null==i&&(i=32),null==o&&(o=1),null==c&&(c=!0),null==h&&(h=0),g=!1,null!=u&&null!=l&&(g=!0),null!=d&&(g=!0,null==f))throw new bp("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(y=t.checkNumSamples(n,i,f,"steps_per_epoch"))&&(v=dh(0,y)),null==a&&(a=1),b=Af(s,m,a,o,h,y,f,i,g,p),w=b.callbackList,x=b.history,w.setModel(t),t.history=x,[4,w.onTrainBegin()];case 1:C.sent(),t.stopTraining_=!1,N=function(o){var a,s,p,h,d;return up(this,function(m){switch(m.label){case 0:return[4,w.onEpochBegin(o)];case 1:if(m.sent(),a={},null==f)return[3,2];throw new wp("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===c)throw new wp("batch shuffling is not implemneted yet");c&&X.shuffle(v),s=Oe(v),p=Ad(y,i),h=function(o){var c;return up(this,function(h){switch(h.label){case 0:return c={},[4,w.onBatchBegin(o,c)];case 1:return h.sent(),Gt(function(){var h=p[o][0],f=p[o][1],d=yh(s,h,f-h);c.batch=o,c.size=f-h;for(var m=kd(n,d),y=e(m),v=0;v<r.length;++v){var b=r[v],w=y[v];c[b]=w,Ht(w)}if(o===p.length-1&&g){var x=t.testLoop(u,l,i);for(v=0;v<r.length;++v)b=r[v],w=x[v],Ht(w),a["val_"+b]=w}}),[4,w.onBatchEnd(o,c)];case 2:return h.sent(),bf(c),t.stopTraining_?[2,"break"]:[2]}})},d=0,m.label=3;case 3:return d<p.length?[5,h(d)]:[3,6];case 4:if("break"===m.sent())return[3,6];m.label=5;case 5:return++d,[3,3];case 6:s.dispose(),m.label=7;case 7:return[4,w.onEpochEnd(o,a)];case 8:return m.sent(),t.stopTraining_?[2,"break"]:[2]}})},S=h,C.label=2;case 2:return S<o?[5,N(S)]:[3,5];case 3:if("break"===C.sent())return[3,5];C.label=4;case 4:return++S,[3,2];case 5:return[4,w.onTrainEnd()];case 6:return C.sent(),[4,t.history.syncData()];case 7:return C.sent(),[2,t.history]}})})}(t,v,y,b,c,r.epochs,r.verbose,N,w,f,r.shuffle,x,r.initialEpoch,null,null,r.yieldEvery)];case 2:return[2,S.sent()];case 3:return t.isTraining=!1,Dd(i,e),Dd(o,n),Dd(u,a),Dd(l,s),[7];case 4:return[2]}})})}function Rd(t){var e=[];t instanceof lt&&(t=[t]);for(var n=0;n<t.length;++n){var r=t[n];if(1===r.rank)e.push(gh(r,1));else{if(0===r.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(r)}}return e}function Dd(t,e){if(null!=t){var n=[];if(e instanceof lt)n.push(e.id);else if(Array.isArray(e))e.forEach(function(t){return n.push(t.id)});else if(null!=e)for(var r in e){var i=e[r];n.push(i.id)}var o=[];if(t instanceof lt)-1===n.indexOf(t.id)&&o.push(t);else if(Array.isArray(t))t.forEach(function(t){-1===n.indexOf(t.id)&&o.push(t)});else if(null!=t)for(var a in t){var s=t[a];-1===n.indexOf(s.id)&&o.push(s)}o.forEach(function(t){t.isDisposed||t.dispose()})}}function Od(t){return Array.isArray(t)}function _d(t){return!function(t){return t instanceof lt}(t)&&!Od(t)}function Md(t,e,n,r,i){if(void 0===r&&(r=!0),void 0===i&&(i=""),null==e||0===e.length){if(null!=t){var o=!1;if(Od(t)&&t.length>0)o=!0;else if(_d(t)){for(var a in t)if(t.hasOwnProperty(a)){o=!0;break}}else o=!0;if(o)throw new bp("Error when checking model "+i+" expected no data, but got "+t)}return[]}if(null==t)return e.map(function(t){return null});var s;if(_d(t)){t=t,s=[];for(var u=0,l=e;u<l.length;u++){var c=l[u];if(null==t[c])throw new bp('No data provided for "'+c+'". Need data for each key in: '+e);s.push(t[c])}}else if(Od(t)){if((t=t).length!==e.length)throw new bp("Error when checking model "+i+": the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see "+e.length+" Tensor(s), but instead got the following list of Tensor(s): "+t);s=t}else{if(t=t,e.length>1)throw new bp("The model "+i+" expects "+e.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+t.shape);s=[t]}if(s=Rd(s),null!=n)for(var p=0;p<e.length;++p)if(null!=n[p]){var h=s[p];if(h.shape.length!==n[p].length)throw new bp("Error when checking "+i+": expected "+e[p]+" to have "+n[p].length+" dimension(s). but got array with shape "+h.shape);for(var f=0;f<n[p].length;++f)if(0!==f||r){var d=h.shape[f],m=n[p][f];if(null!=m&&m>=0&&d!==m)throw new bp("Error when checking "+i+": expected "+e[p]+" to have shape ["+n[p]+"], but got array with shape ["+h.shape+"].")}}return s}function Ld(t,e,n,r,i){var o;if(void 0===r&&(r=!0),void 0===i&&(i=""),Array.isArray(t)){if(t.length!==e.length)throw new bp("Error when checking model "+i+": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see "+e.length+" Tensor(s), but instead got "+t.length+" Tensors(s).");o=t}else{if(e.length>1)throw new bp("The model expects "+e.length+" "+i+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(t.shape)+".");o=[t]}if(null!=n)for(var a=0;a<e.length;++a)if(null!=n[a]){var s=o[a];if(s.shape.length!==n[a].length)throw new bp("Error when checking "+i+": expected "+e[a]+" to have "+n[a].length+" dimension(s), but got array with shape "+JSON.stringify(s.shape));for(var u=0;u<n[a].length;++u)if(0!==u||r){var l=s.shape[u],c=n[a][u];if(null!=c&&c!==l)throw new bp("Error when checking "+i+": expected "+e[a]+" to have shape "+JSON.stringify(n[a])+" but got array with shape "+JSON.stringify(s.shape)+".")}}}var Fd=function(t){function e(e){var n=t.call(this,e)||this;return n.isTraining=!1,n}return ip(e,t),e.prototype.summary=function(t,e,n){if(void 0===n&&(n=console.log),!this.built)throw new bp("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");sd(this,t,e,n)},e.prototype.compile=function(t){var e=this;if(null==t.loss&&(t.loss=[]),this.loss=t.loss,"string"==typeof t.optimizer)this.optimizer_=function(t){var e={Adagrad:function(){return Zc.adagrad(.01)},Adadelta:function(){return Zc.adadelta(1,.95,lp())},Adam:function(){return Zc.adam(.001,.9,.999,lp())},Adamax:function(){return Zc.adamax(.002,.9,.999,lp(),0)},RMSProp:function(){return Zc.rmsprop(.001,.9,0,lp())},SGD:function(){return Zc.sgd(.01)}};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,t in e)return e[t]();throw new bp("Unknown Optimizer "+t)}(t.optimizer),this.isOptimizerOwned=!0;else{if(!(t.optimizer instanceof jc))throw new bp("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=t.optimizer,this.isOptimizerOwned=!1}var n=[];if(Array.isArray(t.loss)||"string"==typeof t.loss||"function"==typeof t.loss)if(Array.isArray(t.loss)){if(t.loss.length!==this.outputs.length)throw new bp("When passing an Array as loss, it should have one entry per model output. The model has "+this.outputs.length+" output(s), but you passed loss="+t.loss+".");var r=t.loss;n=r.map(function(t){return qf(t)})}else{var i=qf(t.loss);this.outputs.forEach(function(t){n.push(i)})}else{for(var o in t.loss=t.loss,t.loss)if(-1===this.outputNames.indexOf(o))throw new bp('Unknown entry in loss dictionary: "'+o+'". Only expected the following keys: '+this.outputNames);for(var a=0,s=this.outputNames;a<s.length;a++){var u=s[a];null==t.loss[u]&&console.warn('Output "'+u+'" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to '+u+" during training"),n.push(qf(t.loss[u]))}}this.lossFunctions=n,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(var l=0;l<this.outputs.length;++l){var c=this.internalOutputShapes[l],p=this.outputNames[l];this.feedOutputNames.push(p),this.feedOutputShapes.push(c),this.feedLossFns.push(this.lossFunctions[l])}var h=[];this.metrics=t.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ih("loss",function(){for(var t=0;t<e.outputs.length;++t)if(-1===h.indexOf(t)){var n=e.lossFunctions[t];e.outputs.length>1&&(e.metricsTensors.push([n,t]),e.metricsNames.push(e.outputNames[t]+"_loss"))}});var f=function(t,e){if(null==t||Array.isArray(t)&&0===t.length)return e.map(function(t){return[]});if(Array.isArray(t))return e.map(function(e){return t});if(null!=t){for(var n=[],r=0,i=e;r<i.length;r++){var o=i[r],a=t.hasOwnProperty(o)?t[o]:[];Array.isArray(a)||(a=[a]),n.push(a)}return n}throw new TypeError("Type of metrics argument not understood. Expected an Array or Object, found: "+t)}(t.metrics,this.outputNames);ih("metric",function(){for(var t=function(t){if(-1!==h.indexOf(t))return"continue";!function(n){for(var r,i,o,a=function(n){if(-1!==["accuracy","acc","crossentropy","ce"].indexOf(n)){var a=e.internalOutputShapes[t];1===a[a.length-1]||e.lossFunctions[t]===Uf?-1!==["accuracy","acc"].indexOf(n)?i=Gf:-1!==["crossentropy","ce"].indexOf(n)&&(i=Yf):e.lossFunctions[t]===Bf?-1!==["accuracy","acc"].indexOf(n)?i=Jf:-1!==["crossentropy","ce"].indexOf(n)&&(i=ad):-1!==["accuracy","acc"].indexOf(n)?i=Hf:-1!==["crossentropy","ce"].indexOf(n)&&(i=id);var s=void 0;-1!==["accuracy","acc"].indexOf(n)?s="acc":-1!==["crossentropy","ce"].indexOf(n)&&(s="ce"),o=i,r=""+s}else{var u=function(t){var e={binaryAccuracy:Gf,categoricalAccuracy:Hf,precision:$f,categoricalCrossentropy:id,sparseCategoricalCrossentropy:ad,mse:Zf,MSE:Qf,mae:td,MAE:ed,mape:nd,MAPE:rd,cosine:od};if("string"==typeof t&&t in e)return e[t];if("string"!=typeof t&&null!=t)return t;throw new bp("Unknown metric "+t)}(n);o=u,r=""+n}var l;ih(r,function(){l=o}),function(t,n,r){e.outputNames.length>1&&(n=e.outputNames[t]+"_"+n),e.metricsNames.push(n),e.metricsTensors.push([r,t])}(t,r,l)},s=0,u=f[t];s<u.length;s++)a(u[s])}()},n=0;n<e.outputs.length;++n)t(n)}),this.collectedTrainableWeights=this.trainableWeights},e.prototype.checkTrainableWeightsConsistency=function(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")},e.prototype.evaluate=function(t,e,n){void 0===n&&(n={});var r=null==n.batchSize?32:n.batchSize;Ed(r);var i=this.standardizeUserData(t,e,!0,r);try{var o=i[0].concat(i[1]);this.makeTestFunction();var a=this.testFunction;return Ep(this.testLoop(a,o,r,n.verbose,n.steps))}finally{Dd(i[0],t),Dd(i[1],e)}},e.prototype.evaluateDataset=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){return this.makeTestFunction(),[2,function(t,e,n){return sp(this,void 0,void 0,function(){var r,i,o,a,s,u,l,c,p,h;return up(this,function(f){switch(f.label){case 0:if(r=null!=(n=n||{}).batches,i=t.testFunction,o=[],n.verbose>0)throw new wp("Verbose mode is not implemented yet.");return X.assert(!r||n.batches>0&&Number.isInteger(n.batches),function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(n.batches)}),function(t){return"function"==typeof t.next}(e)?(s=e,[3,3]):[3,1];case 1:return[4,e.iterator()];case 2:s=f.sent(),f.label=3;case 3:a=s,u=0,l=0,c=function(){var e,s,c,p,h,f;return up(this,function(d){switch(d.label){case 0:return[4,a.next()];case 1:if((e=d.sent()).value){if(s=xd(t,e.value),c=Gt(function(){return i(s)}),Kt(s),0===l)for(f=0;f<c.length;++f)o.push(gp(0));for(p=s[0].shape[0],h=function(t){var e=c[t],n=o[t];o[t]=Gt(function(){return fu(o[t],Iu(gp(p),e))}),l>0&&Kt(n)},f=0;f<c.length;++f)h(f);Kt(c),u+=p,++l}return e.done?(r&&console.warn("Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least `batches` batches (in this case, "+n.batches+" batches). You may need to use the repeat() function when building your dataset."),[2,"break"]):[2]}})},f.label=4;case 4:return!r||l<n.batches?[5,c()]:[3,6];case 5:return"break"===f.sent()?[3,6]:[3,4];case 6:for(p=function(t){var e=o[t];o[t]=Gt(function(){return yu(o[t],gp(u))}),Kt(e)},h=0;h<o.length;++h)p(h);return[2,Ep(o)]}})})}(this,t,e)]})})},e.prototype.checkNumSamples=function(t,e,n,r){var i;if(void 0===r&&(r="steps"),null!=n){if(i=null,null!=e)throw new bp("If "+r+" is set, batchSize must be null or undefined.Got batchSize = "+e)}else{if(null==t)throw new bp("Either the input data should have a defined shape, or "+r+" shoud be specified.");i=Array.isArray(t)?t[0].shape[0]:t.shape[0]}return i},e.prototype.execute=function(t,e){if(Array.isArray(e)&&0===e.length)throw new bp("`outputs` is an empty Array, which is not allowed.");var n=Array.isArray(e),r=n?e:[e],i=this.retrieveSymbolicTensors(r),o=new dd;if(t instanceof lt&&(t=[t]),Array.isArray(t)){if(t.length!==this.inputs.length)throw new bp("The number of inputs provided ("+t.length+") does not match the number of inputs of this model ("+this.inputs.length+").");for(var a=0;a<this.inputs.length;++a)o.add(this.inputs[a],t[a])}else for(var s=0,u=this.inputs;s<u.length;s++){var l=u[s],c=t[l.name];if(null==c)throw new bp("No value is provided for the model's input "+l.name);o.add(l,c)}var p=yd(i,o);return n?p:p[0]},e.prototype.retrieveSymbolicTensors=function(t){for(var e=Np(null,t.length),n=t.length,r=0,i=this.layers;r<i.length;r++){for(var o=i[r],a=Array.isArray(o.output)?o.output:[o.output],s=a.map(function(t){return t.name}),u=0;u<t.length;++u){var l=s.indexOf(t[u]);if(-1!==l&&(e[u]=a[l],n--),0===n)break}if(0===n)break}if(n>0){var c=[];throw e.forEach(function(e,n){null==e&&c.push(t[n])}),new bp("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return e},e.prototype.predictLoop=function(t,e,n){var r=this;return void 0===e&&(e=32),void 0===n&&(n=!1),Gt(function(){var i=r.checkNumSamples(t);if(n)throw new wp("Verbose predictLoop() is not implemented yet.");for(var o=Ad(i,e),a=r.outputs.map(function(t){return[]}),s=function(e){Gt(function(){var n=o[e][0],i=o[e][1],a=Id(t,n,i),s=[];if(Array.isArray(a))for(var u=0;u<a.length;++u)s.push({key:r.inputs[u],value:a[u]});else s.push({key:r.inputs[0],value:a});var l=new dd(s);return yd(r.outputs,l)}).forEach(function(t,e){return a[e].push(t)})},u=0;u<o.length;++u)s(u);return Ep(a.map(function(t){return No(t,0)}))})},e.prototype.predict=function(t,e){void 0===e&&(e={});var n=Rd(t);Ld(n,this.inputNames,this.feedInputShapes,!1);try{var r=null==e.batchSize?32:e.batchSize;return Ed(r),this.predictLoop(n,r)}finally{Dd(n,t)}},e.prototype.predictOnBatch=function(t){return Ld(t,this.inputNames,this.feedInputShapes,!0),this.predictLoop(t,t.shape[0])},e.prototype.standardizeUserData=function(t,e,n,r){if(void 0===n&&(n=!0),null==this.optimizer_)throw new vp("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");for(var i=[],o=0;o<this.feedOutputShapes.length;++o){var a=this.feedOutputShapes[o];this.feedLossFns[o]===Bf?i.push(a.slice(0,a.length-1).concat([1])):i.push(a)}if(function(t,e,n){var r=_p(t.map(function(t){return t.shape[0]}));r.sort();var i=_p(e.map(function(t){return t.shape[0]}));if(i.sort(),r.length>1)throw new bp("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(t){return t.shape})));if(i.length>1)throw new bp("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(t){return t.shape})));if(r.length>0&&i.length>0&&!X.arraysEqual(r,i))throw new bp("Input Tensors should have the same number of samples as target Tensors. Found "+r[0]+" input sample(s) and "+i[0]+" target sample(s).")}(t=Md(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=Md(e,this.feedOutputNames,i,!1,"target")),function(t,e,n){for(var r=[Rf,Uf,Pf],i=0;i<t.length;++i){var o=t[i],a=e[i],s=n[i];if(null!=a){if(a===Pf&&1===o.shape[o.shape.length-1])throw new bp("You are passing a target array of shape "+o.shape+" while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");if(-1!==r.indexOf(a))for(var u=o.shape.slice(1),l=s.slice(1),c=0;c<u.length;++c){var p=u[c],h=l[c];if(null!=h&&p!==h)throw new bp("A target Tensor with shape "+o.shape+" was passed for an output of shape "+s+", while using a loss function that expects targets to have the same shape as the output.")}}}}(e,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&t[0].shape[0]%r!=0)throw new bp("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+r+". Found: "+t[0].shape[0]+" sample(s).");return[t,e,null]},e.prototype.testLoop=function(t,e,n,r,i){var o=this;return void 0===r&&(r=0),Gt(function(){var a=o.checkNumSamples(e,n,i,"steps"),s=[];if(r>0)throw new wp("Verbose mode is not implemented yet.");if(null!=i)throw new wp("steps mode in testLoop() is not implemented yet");for(var u=Ad(a,n),l=Oe(dh(0,a)),c=0;c<u.length;++c){var p=u[c][0],h=u[c][1],f=yh(l,p,h-p),d=kd(e,f),m=t(d);if(0===c)for(var g=0;g<m.length;++g)s.push(gp(0));for(g=0;g<m.length;++g){var y=m[g];s[g]=fu(s[g],Iu(gp(h-p),y))}}for(g=0;g<s.length;++g)s[g]=yu(s[g],gp(a));return s})},e.prototype.getDedupedMetricsNames=function(){for(var t=this.metricsNames,e=[],n=0;n<t.length;++n){var r=t[n],i=r;Cp(t,r)>1&&(i+="_"+Cp(t.slice(0,n),r)),e.push(i)}return e},e.prototype.makeTrainFunction=function(){var t=this;return function(e){var n=e.slice(0,t.inputs.length),r=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),i=[],o=t.collectedTrainableWeights.map(function(t){return t.read()});return[t.optimizer_.minimize(function(){for(var e=[],o=0;o<t.inputs.length;++o)e.push({key:t.inputs[o],value:n[o]});var a,s=new dd(e),u=yd(t.outputs,s,{training:!0});for(o=0;o<t.lossFunctions.length;++o){var l=(0,t.lossFunctions[o])(r[o],u[o]);Ys(l),a=0===o?l:fu(a,l)}for(o=0;o<t.metricsTensors.length;++o){var c=t.metricsTensors[o][0],p=t.metricsTensors[o][1],h=Ys(c(r[p],u[p]));Ht(h),i.push(h)}return a=Ys(a),t.calculateLosses().forEach(function(t){a=fu(a,t)}),a},!0,o)].concat(i)}},e.prototype.makeTestFunction=function(){var t=this;this.testFunction=function(e){return Gt(function(){for(var n,r=[],i=e.slice(0,t.inputs.length),o=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),a=[],s=0;s<t.inputs.length;++s)a.push({key:t.inputs[s],value:i[s]});var u=new dd(a),l=yd(t.outputs,u);for(s=0;s<t.lossFunctions.length;++s){var c=t.lossFunctions[s],p=Ys(c(o[s],l[s]));n=0===s?p:fu(n,p),r.push(n)}for(s=0;s<t.metricsTensors.length;++s){var h=t.metricsTensors[s][0],f=t.metricsTensors[s][1],d=Ys(h(o[f],l[f]));r.push(d)}return r})}},e.prototype.fit=function(t,e,n){return void 0===n&&(n={}),sp(this,void 0,void 0,function(){return up(this,function(r){return[2,Td(this,t,e,n)]})})},e.prototype.fitDataset=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){return[2,Sd(this,t,e)]})})},e.prototype.trainOnBatch=function(t,e){return sp(this,void 0,void 0,function(){var n,r,i,o,a,s,u,l,c;return up(this,function(p){switch(p.label){case 0:n=this.standardizeUserData(t,e),r=n[0],i=n[1],o=this.makeTrainFunction(),a=o(r.concat(i)),s=[],u=0,l=a,p.label=1;case 1:return u<l.length?[4,l[u].data()]:[3,4];case 2:c=p.sent(),s.push(c[0]),p.label=3;case 3:return u++,[3,1];case 4:return Kt(a),[2,Ep(s)]}})})},e.prototype.getNamedWeights=function(t){for(var e={},n=null!=t&&t.trainableOnly,r=n?this.trainableWeights:this.weights,i=this.getWeights(n),o=0;o<r.length;++o)n&&!r[o].trainable||(e[r[o].originalName]=i[o]);return e},Object.defineProperty(e.prototype,"stopTraining",{set:function(t){this.stopTraining_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"optimizer",{get:function(){return this.optimizer_},set:function(t){this.optimizer_!==t&&(this.optimizer_=t,this.isOptimizerOwned=!1)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var e=t.prototype.dispose.call(this);if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){var n=np().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=n-np().numTensors}return e},e.prototype.save=function(t,e){return sp(this,void 0,void 0,function(){var n,r,i,o,a;return up(this,function(s){switch(s.label){case 0:if("string"==typeof t){if(0===(n=Tc.getSaveHandlers(t)).length)throw new bp("Cannot find any save handlers for URL '"+t+"'");if(n.length>1)throw new bp("Found more than one ("+n.length+") save handlers for URL '"+t+"'");t=n[0]}if(null==t.save)throw new bp("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,Tc.encodeWeights(this.getNamedWeights(e))];case 1:return r=s.sent(),i=!1,o=null,a=this.toJSON(o,i),[2,t.save({modelTopology:a,weightData:r.data,weightSpecs:r.specs,format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v1.0.1",convertedBy:null})]}})})},e.className="Model",e}(function(t){function e(n){var r=t.call(this,{})||this;if(r.containerNodes=new Set,r.name=n.name,null==r.name){var i=r.getClassName().toLowerCase();r.name=fp(i)}if(r.supportsMasking=!1,r.trainable_=!0,r.updatable=!0,Array.isArray(n.inputs)?r.inputs=n.inputs.slice():r.inputs=[n.inputs],Array.isArray(n.outputs)?r.outputs=n.outputs.slice():r.outputs=[n.outputs],_p(r.inputs).length!==r.inputs.length)throw new bp("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+r.inputs.map(function(t){return t.name}));_p(r.outputs).length!==r.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+r.outputs.map(function(t){return t.name})),r.inputLayers=[],r.inputLayersNodeIndices=[],r.inputLayersTensorIndices=[],r.outputLayers=[],r.outputLayersNodeIndices=[],r.outputLayersTensorIndices=[],r.layers=[];for(var o=0,a=r.outputs;o<a.length;o++){var s=(I=a[o]).sourceLayer,u=I.nodeIndex,l=I.tensorIndex;r.outputLayers.push(s),r.outputLayersNodeIndices.push(u),r.outputLayersTensorIndices.push(l)}for(var c=0,p=r.inputs;c<p.length;c++)s=(I=p[c]).sourceLayer,u=I.nodeIndex,l=I.tensorIndex,Sp(0===u,"input layer has >1 nodes"),Sp(0===l,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(u),r.inputLayersTensorIndices.push(l);r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var h=0;h<r.inputLayers.length;h++){if(!((s=r.inputLayers[h])instanceof gf))throw new TypeError("Input layers to a LayersModel must be InputLayer objects. Received inputs: "+n.inputs+". Input "+h+" (0-based) originates from layer type "+s.getClassName()+".");r.inputNames.push(s.name),r.feedInputShapes.push(s.batchInputShape),r.feedInputNames.push(s.name)}for(var f=0,d=r.outputLayers;f<d.length;f++)s=d[f],r.outputNames.push(s.name);r.internalInputShapes=r.inputs.map(function(t){return t.shape}),r.internalOutputShapes=r.outputs.map(function(t){return t.shape});for(var m={},g={},y={},v={},b={},w=[],x=function(t,n,i,o,a,s){null!=o&&null!=a&&null!=s||(o=t.sourceLayer,a=t.nodeIndex,s=t.tensorIndex);var u=o.inboundNodes[a];if(-1!==i.indexOf(u))throw new vp("The tensor "+t.name+' at layer "'+o.name+'" is part of a cycle.');if(-1===n.indexOf(u)){r.containerNodes.add(e.nodeKey(o,a)),o.id in b||(b[o.id]=Object.keys(b).length),-1===i.indexOf(u)&&i.push(u);for(var l=u.inboundLayers.length,c=0;c<l;c++){var p=u.inputTensors[c],h=u.inboundLayers[c],f=u.nodeIndices[c],d=u.tensorIndices[c];x(p,n,i,h,f,d)}for(n.push(u);i.indexOf(u)>=0;)i.splice(i.indexOf(u),1);w.push(u)}},N=[],S=[],C=0,E=r.outputs;C<E.length;C++){var I=E[C];x(I,N,S)}for(var k=0,A=w.slice().reverse();k<A.length;k++){g[(Y=A[k]).id]=Y,Y.id in m||(m[Y.id]=0);var T=m[Y.id],R=null==y[Y.outboundLayer.id]?0:y[Y.outboundLayer.id];for(T=Math.max(T,R),y[Y.outboundLayer.id]=T,v[Y.outboundLayer.id]=Y.outboundLayer,m[Y.id]=T,h=0;h<Y.inboundLayers.length;h++){var D=Y.inboundLayers[h],O=(u=Y.nodeIndices[h],D.inboundNodes[u]),_=null==m[O.id]?0:m[O.id];m[O.id]=Math.max(T+1,_),g[O.id]=O}}var M={};for(var L in m)(T=m[L])in M||(M[T]=[]),M[T].push(g[L]);var F={};for(var z in y)(T=y[z])in F||(F[T]=[]),F[T].push(v[z]);var P=Object.keys(F).map(function(t){return parseInt(t,10)}).sort(Op);r.layers=[];for(var B=0,U=P;B<U.length;B++){var W=F[T=U[B]];W.sort(function(t,e){var n=b[t.id],r=b[e.id];return n<r?-1:n>r?1:0});for(var V=0,j=W;V<j.length;V++)s=j[V],r.layers.push(s)}r.layersByDepth=F,P=Object.keys(M).map(function(t){return parseInt(t,10)}).sort(Op);for(var q=r.inputs.slice(),G=[],H=0,K=P;H<K.length;H++)for(var $=0,X=M[T=K[H]];$<X.length;$++){var Y;if(null!=(s=(Y=X[$]).outboundLayer)){for(var J=0,Z=Y.inputTensors;J<Z.length;J++)if(I=Z[J],-1===q.indexOf(I))throw new vp("Graph disconnected: cannot obtain value for tensor "+I+' at layer "'+s.name+'". The following previous layers were accessed without issue: '+G);for(var Q=0,tt=Y.outputTensors;Q<tt.length;Q++)I=tt[Q],q.push(I);G.push(s.name)}}r.nodesByDepth=M;for(var et=r.layers.map(function(t){return t.name}),nt=function(t){var e=et.filter(function(e){return e===t}).length;if(1!==e)throw new vp('The name "'+t+'" is used '+e+" times in the model. All layer names should be unique. Layer names: "+JSON.stringify(et))},rt=0,it=et;rt<it.length;rt++)nt(it[rt]);return r.outboundNodes=[],r.inboundNodes=[],new hf({outboundLayer:r,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:r.inputs,outputTensors:r.outputs,inputMasks:r.inputs.map(function(t){return null}),outputMasks:r.outputs.map(function(t){return null}),inputShapes:r.inputs.map(function(t){return t.shape}),outputShapes:r.outputs.map(function(t){return t.shape})}),r.built=!0,r._refCount=1,r}return ip(e,t),e.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Container '"+this.name+"' is already disposed.")},e.prototype.dispose=function(){this.assertNotDisposed();var t={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount)for(var e=0,n=this.layers;e<n.length;e++){var r=n[e];t.numDisposedVariables+=r.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){if(this._trainableWeights.length>0)throw new bp("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e];t=t.concat(r.trainableWeights)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e];t.push.apply(t,r.nonTrainableWeights)}if(!this.trainable){for(var i=[],o=0,a=this.layers;o<a.length;o++)r=a[o],i.push.apply(i,r.trainableWeights);return i.concat(t)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),e.prototype.loadWeights=function(t,e){void 0===e&&(e=!0);for(var n={},r=0,i=0,o=this.layers;i<o.length;i++)for(var a=0,s=o[i].weights;a<s.length;a++){var u=s[a];if(null!=n[u.originalName])throw new bp("Duplicate weight name: "+u.originalName);n[u.originalName]=u,r++}var l=[];for(var c in t){if(null!=n[c])l.push([n[c],t[c]]);else if(e)throw new bp("Provided weight data has no target variable: "+c);delete n[c]}if(e){var p=[];for(var h in n)p.push(h);if(p.length>0)throw new bp(p.length+" of "+r+" weights are not set: "+p)}uf(l)},e.prototype.updatedConfig=function(){var t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers 1.0.1",e.backend="TensorFlow.js",e},e.prototype.toJSON=function(t,e){void 0===e&&(e=!0);var n=function t(e,n){if(null===e||void 0===e)return null;if("string"==typeof e)return kp(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var r=[],i=e.length,o=0;o<i;++o){var a=e[o];hd(n,o,a)?r.push(a):r.push(t(a,n))}return r}for(var s={},u=0,l=Object.keys(e);u<l.length;u++){var c=l[u],p=e[c];s[kp(c)]="name"!==c&&"className"!==c||"string"!=typeof p?t(p,c):p}return s}(this.updatedConfig());return e?JSON.stringify(n):n},e.prototype.call=function(t,e){var n=this;return Gt(function(){t=Ip(t);for(var r=new dd,i=0;i<n.inputs.length;++i)r.add(n.inputs[i],t[i]);return yd(n.outputs,r,e)})},e.prototype.computeMask=function(t,e){var n=this;return Gt(function(){var r;return t=Ip(t),r=null==e?Np(null,t.length):Ip(e),n.runInternalGraph(t,r)[1]})},e.prototype.computeOutputShape=function(t){var e=tf(t);if(e.length!==this.inputLayers.length)throw new bp("Invalid inputShape argument "+t+": model has "+this.inputLayers.length+" tensor inputs.");for(var n={},r=0;r<e.length;r++){var i=this.inputLayers[r],o=e[r];n[S=i.name+"_0_0"]=o}var a=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(Op);if(a.length>1)for(var s=0,u=a;s<u.length;s++)for(var l=u[s],c=0,p=this.nodesByDepth[l];c<p.length;c++){var h=p[c];if(i=h.outboundLayer,-1===this.inputLayers.map(function(t){return t.id}).indexOf(i.id)){for(var f=[],d=0;d<h.inboundLayers.length;d++){var m=h.inboundLayers[d],g=h.nodeIndices[d],y=h.tensorIndices[d],v=n[S=m.name+"_"+g+"_"+y];f.push(v)}var b=tf(i.computeOutputShape(Ep(f))),w=i.inboundNodes.indexOf(h);for(d=0;d<b.length;d++)n[S=i.name+"_"+w+"_"+d]=b[d]}}var x=[],N=[];for(r=0;r<this.outputLayers.length;r++){i=this.outputLayers[r],w=this.outputLayersNodeIndices[r],y=this.outputLayersTensorIndices[r];var S=i.name+"_"+w+"_"+y;N.push(S)}for(r=0;r<N.length;r++){var C=N[r];Sp(C in n),x.push(n[C])}return Ep(x)},e.prototype.runInternalGraph=function(t,e){null==e&&(e=Np(null,t.length));for(var n={},r=0;r<this.inputs.length;++r){var i=this.inputs[r],o=t[r],a=e[r];n[i.id]=[o,a]}for(var s=0,u=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(Op);s<u.length;s++)for(var l=u[s],c=0,p=this.nodesByDepth[l];c<p.length;c++){for(var h=p[c],f=h.outboundLayer,d=h.inputTensors,m=h.outputTensors,g=new Array,y=0,v=d;y<v.length;y++)(i=v[y]).id in n&&g.push(n[i.id]);if(g.length===d.length){var b={},w=void 0,x=void 0,N=void 0,S=void 0;if(null!=h.callArgs&&(b=h.callArgs),1===g.length){var C=g[0],E=C[0],I=C[1];null==b.mask&&(b.mask=I),N=Ip(f.call(E,b)),S=Ip(f.computeMask(E,I)),w=[E],x=[I]}else w=g.map(function(t){return t[0]}),x=g.map(function(t){return t[1]}),null==b.mask&&(b.mask=x),N=Ip(f.call(w,b)),S=Ip(f.computeMask(w,x));if(f.activityRegularizer)throw new wp("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(r=0;r<m.length;++r)i=m[r],o=N[r],a=S[r],n[i.id]=[o,a]}}for(var k=[],A=[],T=[],R=0,D=this.outputs;R<D.length;R++){Sp((i=D[R]).id in n,"Could not compute output "+i.name+" : "+i.id);var O=n[i.id],_=O[0];a=O[1],T.push(_.shape),k.push(_),A.push(a)}return[k,A,T]},e.prototype.buildNodeConversionMap=function(t){for(var n,r={},i=0,o=this.layers;i<o.length;i++){var a=o[i];n=a instanceof e?1:0;for(var s=0;s<a.inboundNodes.length;s++){var u=e.nodeKey(a,s);this.containerNodes.has(u)&&(r[u]=n,n+=1)}}return r},e.prototype.getLayer=function(t,e){if(null!=e){if(this.layers.length<=e)throw new bp("Was asked to retrieve layer at index "+e+", but model only has "+this.layers.length+" layer(s).");return this.layers[e]}if(null==t)throw new bp("Provide either a layer name or layer index");for(var n=0,r=this.layers;n<r.length;n++){var i=r[n];if(i.name===t)return i}throw new bp("No such layer: "+t)},e.prototype.calculateLosses=function(){var t=this;return Gt(function(){for(var n=[],r=0,i=t.layers;r<i.length;r++)for(var o=i[r],a=0;a<o.inboundNodes.length;++a){var s=e.nodeKey(o,a);t.containerNodes.has(s)&&n.push.apply(n,o.calculateLosses())}return n})},e.prototype.getConfig=function(){for(var t={name:this.name},n=this.buildNodeConversionMap(this.layers),r=[],i=0,o=this.layers;i<o.length;i++){for(var a=(w=o[i]).getClassName(),s=w.getConfig(),u=[],l=0;l<w.inboundNodes.length;l++){var c=w.inboundNodes[l],p=e.nodeKey(w,l),h={};if(this.containerNodes.has(p)){if(c.callArgs)try{JSON.stringify(c.callArgs),h=c.callArgs}catch(t){console.warn("Layer "+w.name+" was passed non-serializable keyword arguments: "+c.callArgs+". They will not be included in the serialized model (and thus will be missing at deserialization time)."),h={}}if(c.inboundLayers.length>0){for(var f=[],d=0;d<c.inboundLayers.length;d++){var m=c.inboundLayers[d],g=c.nodeIndices[d],y=c.tensorIndices[d];null==(N=n[e.nodeKey(m,g)])&&(N=0),f.push([m.name,N,y,h])}u.push(f)}}}var v={};v.name=w.name,v.className=a,v.config=s,v.inboundNodes=u,r.push(v)}t.layers=r;var b=[];for(d=0;d<this.inputLayers.length;d++){var w=this.inputLayers[d];g=this.inputLayersNodeIndices[d],p=e.nodeKey(w,g),this.containerNodes.has(p)&&(null!==(N=n[p])&&void 0!==N||(N=0),y=this.inputLayersTensorIndices[d],b.push([w.name,N,y]))}t.inputLayers=b;var x=[];for(d=0;d<this.outputLayers.length;d++){var N;if(w=this.outputLayers[d],g=this.outputLayersNodeIndices[d],p=e.nodeKey(w,g),this.containerNodes.has(p))null!==(N=n[p])&&void 0!==N||(N=0),y=this.outputLayersTensorIndices[d],x.push([w.name,N,y])}return t.outputLayers=x,t},e.fromConfig=function(t,e,n,r){void 0===n&&(n={}),void 0===r&&(r=!1);var i={},o={};function a(t,e){t.name in o?o[t.name].push(e):o[t.name]=[e]}function s(t,e){for(var n,r=[],o=0,s=e;o<s.length;o++){var u=s[o],l=u[0],c=u[1],p=u[2];if(3===u.length)n={};else{if(4!==u.length)throw new bp("Improperly formatted model config for layer "+JSON.stringify(t)+": "+JSON.stringify(u));n=u[3]}if(!(l in i))return void a(t,e);var h=i[l];if(h.inboundNodes.length<=c)return void a(t,e);var f=h.inboundNodes[c];r.push(f.outputTensors[p])}r.length>0&&t.apply(Ep(r),n)}function u(t){var n=t.name,o=pd(t,null!=e.customObjects?e.customObjects:{});o.setFastWeightInitDuringBuild(r),i[n]=o;for(var s=0,u=t.inboundNodes;s<u.length;s++){var l=u[s];if(!(l instanceof Array))throw new bp("Corrupted configuration, expected array for nodeData: "+l);a(o,l)}}for(var l=e.name,c=e.layers,p=0,h=c;p<h.length;p++)u(m=h[p]);for(;!Mp(o);)for(var f=0,d=c;f<d.length;f++){var m=d[f];if((T=i[m.name]).name in o){var g=o[T.name];delete o[T.name];for(var y=0,v=g;y<v.length;y++)s(T,v[y])}}for(var b=[],w=[],x=0,N=e.inputLayers;x<N.length;x++){var S=(m=N[x])[0],C=m[1],E=m[2];Sp(S in i);var I=(T=i[S]).inboundNodes[C].outputTensors;b.push(I[E])}for(var k=0,A=e.outputLayers;k<A.length;k++){var T;S=(m=A[k])[0],C=m[1],E=m[2],Sp(S in i),I=(T=i[S]).inboundNodes[C].outputTensors,w.push(I[E])}return new t({inputs:b,outputs:w,name:l})},Object.defineProperty(e.prototype,"stateful",{get:function(){if(this._stateful)throw new bp("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(var t=0,e=this.layers;t<e.length;t++)if(e[t].stateful)return!0;return!1},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){var t=this;Gt(function(){t.layers.forEach(function(t){t.stateful&&t.resetStates()})})},e}(df));function zd(t,e){return sp(this,void 0,void 0,function(){var n;return up(this,function(r){if(null==e&&(e={}),"string"==typeof t){if(0===(n=Tc.getLoadHandlers(t)).length)n.push(Tc.browserHTTPRequest(t,e));else if(n.length>1)throw new bp("Found more than one ("+n.length+") load handlers for URL '"+t+"'");t=n[0]}return[2,function(t,e,n){return sp(this,void 0,void 0,function(){var r,i,o,a,s,u;return up(this,function(l){switch(l.label){case 0:if(null==n&&(n={}),null==t.load)throw new bp("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,t.load()];case 1:if(r=l.sent(),null!=(i=r.modelTopology).model_config&&(i=i.model_config),o=null==n.strict||n.strict,a=null!=r.weightData&&null!=r.weightSpecs&&o,s=pd(fd(i),e,a),null!=r.weightData){if(null==r.weightSpecs)throw new bp("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");u=Tc.decodeWeights(r.weightData,r.weightSpecs),s.loadWeights(u,o),Kt(u)}return[2,s]}})})}(t,void 0,e)]})})}zc.registerClass(Fd);var Pd=function(t){function e(e){var n=t.call(this,{inputs:[],outputs:[]})||this;if(e=e||{},n.trainable=!0,n._updatable=!0,n.built=!1,n.name=null!=e.name?e.name:fp("sequential_"),null!=e.layers)for(var r=0,i=e.layers;r<i.length;r++){var o=i[r];n.add(o)}return n}return ip(e,t),e.prototype.checkShape=function(t){if(t.inboundNodes[0].outputTensors[0].shape.some(function(t){return t<0}))throw new bp("Negative dimension size caused by adding layer "+t.name+" with input shape ["+t.inboundNodes[0].inputTensors[0].shape+"]")},e.prototype.add=function(t){var n,r=t instanceof e||t instanceof Fd;if(r){if(1!==(n=t).outputs.length)throw new bp("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new bp("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===t.inboundNodes.length){if(null==t.batchInputShape)throw new bp("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var i=yf({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(i)}if(r)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==t.inboundNodes.length)throw new bp("A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer "+t.name+" which has "+t.inboundNodes.length+" pre-existing inbound connections.");if(1!==t.inboundNodes[0].outputTensors.length)throw new bp("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=function t(e,n,r){if((null==n||null!=r&&r>0)&&(n=e.sourceLayer,r=e.nodeIndex),0===n.inboundNodes.length)return[e];var i=n.inboundNodes[r];if(0===i.inboundLayers.length)return i.inputTensors;for(var o=[],a=0;a<i.inboundLayers.length;a++)for(var s=0,u=t(i.inputTensors[a],i.inboundLayers[a],i.nodeIndices[a]);s<u.length;s++){var l=u[s];-1===o.indexOf(l)&&o.push(l)}return o}(this.outputs[0])}this.inboundNodes=[],new hf({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Np(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(function(t){return t.shape}),outputShapes:this.outputs[0].shape})}else{var o=t.apply(this.outputs[0]);if(Array.isArray(o))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[o],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1},e.prototype.pop=function(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{var t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}},e.prototype.call=function(t,e){return null==this.model&&this.build(),this.model.call(t,e)},e.prototype.build=function(t){if(nf(t),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Fd({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.model.updatable=this.updatable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0},e.prototype.countParams=function(){return this.built||this.build(),t.prototype.countParams.call(this)},e.prototype.summary=function(e,n,r){void 0===r&&(r=console.log),this.built||this.build(),t.prototype.summary.call(this,e,n,r)},e.prototype.setWeights=function(t){null==this.model&&this.build(),this.model.setWeights(t)},Object.defineProperty(e.prototype,"updatable",{get:function(){return this._updatable},set:function(t){this.built&&(this.model.updatable=t),this._updatable=t},enumerable:!0,configurable:!0}),e.prototype.evaluate=function(t,e,n){if(void 0===n&&(n={}),!this.built)throw new vp("The model needs to be compiled before being used.");return this.model.evaluate(t,e,n)},e.prototype.evaluateDataset=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){if(!this.built)throw new vp("The model needs to be compiled before being used.");return[2,this.model.evaluateDataset(t,e)]})})},e.prototype.predict=function(t,e){return void 0===e&&(e={}),null==this.model&&this.build(),this.model.predict(t,e)},e.prototype.predictOnBatch=function(t){return null==this.model&&this.build(),this.model.predictOnBatch(t)},e.prototype.compile=function(t){this.build(),this.model.compile(t),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames},Object.defineProperty(e.prototype,"optimizer",{get:function(){return this.model.optimizer},set:function(t){this.model.optimizer=t},enumerable:!0,configurable:!0}),e.prototype.fit=function(t,e,n){return void 0===n&&(n={}),sp(this,void 0,void 0,function(){return up(this,function(r){if(!this.built)throw new vp("The model needs to be compiled before being used.");return[2,this.model.fit(t,e,n)]})})},e.prototype.fitDataset=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){if(!this.built)throw new vp("The model needs to be compiled before being used.");return[2,this.model.fitDataset(t,e)]})})},e.prototype.trainOnBatch=function(t,e){return sp(this,void 0,void 0,function(){return up(this,function(n){return[2,this.model.trainOnBatch(t,e)]})})},e.fromConfig=function(t,n,r,i){var o;void 0===r&&(r={}),void 0===i&&(i=!1);var a={};if(n instanceof Array){if(null==n[0].className||"Merge"===n[0].className)throw new bp("Legacy serialization format not supported yet.");o=n}else X.assert(null!=n.layers,function(){return"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."}),o=n.layers,delete n.layers,a=n;var s=new t(a);if(!(s instanceof e))throw new wp("Sequential.fromConfig called on non-Sequential input: "+s);for(var u=0,l=o;u<l.length;u++){var c=pd(l[u],void 0,i);i&&c.setFastWeightInitDuringBuild(!0),s.add(c)}return s},Object.defineProperty(e.prototype,"stopTraining",{set:function(t){this.model.stopTraining=t},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e],i={};i.className=r.getClassName(),i.config=r.getConfig(),t.push(i)}return t},e.className="Sequential",e}(Fd);function Bd(t){return yf(t)}zc.registerClass(Pd);var Ud=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.getConfig=function(){return{}},e}(zc.Serializable),Wd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=1),function(t,e){if(void 0===e&&(e=1),1!==e)throw new wp("Support for alpha values other than 1 ("+e+") is not implemented yet.");return Uu(t)}(t,e)},e.className="elu",e}(Ud);zc.registerClass(Wd);var Vd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return qu(t)},e.className="selu",e}(Ud);zc.registerClass(Vd);var jd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return ju(t)},e.className="relu",e}(Ud);zc.registerClass(jd);var qd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return Gt(function(){return Nu(gp(6),ju(t))})},e.className="relu6",e}(Ud);zc.registerClass(qd);var Gd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return t},e.className="linear",e}(Ud);zc.registerClass(Gd);var Hd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return Fa(t)},e.className="sigmoid",e}(Ud);zc.registerClass(Hd);var Kd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return function(t){return Gt(function(){var e=fu(gp(.5),Iu(gp(.2),t));return Na(e,0,1)})}(t)},e.className="hardSigmoid",e}(Ud);zc.registerClass(Kd);var $d=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return Ua(t)},e.className="softplus",e}(Ud);zc.registerClass($d);var Xd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return function(t){return Gt(function(){return yu(t,fu(gp(1),da(t)))})}(t)},e.className="softsign",e}(Ud);zc.registerClass(Xd);var Yd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t){return Ga(t)},e.className="tanh",e}(Ud);zc.registerClass(Yd);var Jd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=-1),Ee(t,e)},e.className="softmax",e}(Ud);function Zd(t){return t.getClassName()}function Qd(t,e){return void 0===e&&(e={}),Dp(t,zc.SerializationMap.getMap().classNameMap,e,"activation")}function tm(t){var e;return null==t?Qd(e={className:"linear",config:{}}):"string"==typeof t?((e={}).className=t,e.config={},Qd(e)):t instanceof Ud?t:Qd(t)}zc.registerClass(Jd);var em=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e}(zc.Serializable),nm=function(t){function e(e){var n=t.call(this)||this,r=null==e||null==e.l1?.01:e.l1,i=null==e||null==e.l2?.01:e.l2;return n.hasL1=0!==r,n.hasL2=0!==i,n.l1=gp(r),n.l2=gp(i),n}return ip(e,t),e.prototype.apply=function(t){var e=this;return Gt(function(){var n=Be([1]);return e.hasL1&&(n=fu(n,Qs(Iu(e.l1,da(t))))),e.hasL2&&(n=fu(n,Qs(Iu(e.l2,Ih(t))))),n.asScalar()})},e.prototype.getConfig=function(){return{l1:this.l1.dataSync()[0],l2:this.l2.dataSync()[0]}},e.fromConfig=function(t,e){return new t({l1:e.l1,l2:e.l2})},e.className="L1L2",e}(em);zc.registerClass(nm);var rm={l1l2:"L1L2"};function im(t){return Rp(t)}function om(t,e){return void 0===e&&(e={}),Dp(t,zc.SerializationMap.getMap().classNameMap,e,"regularizer")}function am(t){return null==t?null:"string"==typeof t?om({className:t in rm?rm[t]:t,config:{}}):t instanceof em?t:om(t)}var sm=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.supportsMasking=!0,null!=e&&(n.maxValue=e.maxValue),n}return ip(e,t),e.prototype.call=function(t,e){t=ef(t);var n=ju(t);return null!=this.maxValue&&(n=Na(n,0,this.maxValue)),n},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={maxValue:this.maxValue},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ReLU",e}(df);zc.registerClass(sm);var um=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_ALPHA=.3,null==e&&(e={}),n.alpha=null==e.alpha?n.DEFAULT_ALPHA:e.alpha,n}return ip(e,t),e.prototype.call=function(t,e){var n=ef(t);return Wu(n,this.alpha)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LeakyReLU",e}(df);zc.registerClass(um);var lm=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;if(n.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),n.supportsMasking=!0,n.alphaInitializer=Jh(e.alphaInitializer||n.DEFAULT_ALPHA_INITIALIZER),n.alphaRegularizer=am(e.alphaRegularizer),n.alphaConstraint=Kp(e.alphaConstraint),null==e.sharedAxes)n.sharedAxes=null;else if(Array.isArray(e.sharedAxes))n.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new bp("Expected sharedAxes to be a number or an array of numbers, but got "+e.sharedAxes);n.sharedAxes=[e.sharedAxes]}return n}return ip(e,t),e.prototype.build=function(t){var e=(t=nf(t)).slice(1);if(null!=this.sharedAxes)for(var n=0,r=this.sharedAxes;n<r.length;n++)e[(o=r[n])-1]=1;this.alpha=this.addWeight("alpha",e,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);var i={};if(null!=this.sharedAxes)for(var o=1;o<t.length;++o)i[o]=t[o];this.inputSpec=[new lf({ndim:t.length,axes:i})],this.built=!0},e.prototype.call=function(t,e){return t=ef(t),Vu(t,this.alpha.read())},e.prototype.getConfig=function(){var e={alphaInitializer:Yh(this.alphaInitializer),alphaRegularizer:im(this.alphaRegularizer),alphaConstraint:Gp(this.alphaConstraint),sharedAxes:this.sharedAxes},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="PReLU",e}(df);zc.registerClass(lm);var cm=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;if(n.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==n.DEFAULT_ALPHA)throw new wp("Non-default alpha value ("+e.alpha+") is not supported by the ELU layer yet.");return n.alpha=null==e.alpha?n.DEFAULT_ALPHA:e.alpha,n}return ip(e,t),e.prototype.call=function(t,e){var n=ef(t);return Uu(n)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ELU",e}(df);zc.registerClass(cm);var pm=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_THETA=1,null==e&&(e={}),n.theta=null==e.theta?n.DEFAULT_THETA:e.theta,n.thetaTensor=gp(n.theta),n}return ip(e,t),e.prototype.call=function(t,e){var n=ef(t);return n.mul(mh(n.greater(this.thetaTensor),"float32"))},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={theta:this.theta},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ThresholdedReLU",e}(df);zc.registerClass(pm);var hm=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_AXIS=1,null==e&&(e={}),n.softmax=(new Jd).apply,n.axis=null==e.axis?n.DEFAULT_AXIS:e.axis,n}return ip(e,t),e.prototype.call=function(t,e){var n=ef(t);return this.softmax(n,this.axis)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={axis:this.axis},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Softmax",e}(df);function fm(t,e,n){if("number"==typeof t)return Np(t,e);if(t.length!==e)throw new bp("The "+n+" argument must be a tuple of "+e+" integers. Received: "+t.length+" elements.");for(var r=0;r<e;++r){var i=t[r];if(!lh(i))throw new bp("The "+n+" argument must be a tuple of "+e+" integers. Received: "+JSON.stringify(t)+" including a non-integer number "+i)}return t}function dm(t,e,n,r,i){return void 0===i&&(i=1),null==t?t:(o="same"===n?t:t-(e+(e-1)*(i-1))+1,Math.floor((o+r-1)/r));var o}function mm(t,e,n,r){if(null==t)return null;if("valid"===r)t=t*e+fh([n-e,0]);else{if("same"!==r)throw new bp("Unsupport padding mode: "+r+".");t*=e}return t}function gm(t,e){return Gt(function(){return th(e),"channelsFirst"===e?Gu(t,[0,2,3,1]):t})}zc.registerClass(hm);var ym=function(t){function e(n,r){var i=t.call(this,r)||this;if(i.bias=null,i.DEFAULT_KERNEL_INITIALIZER="glorotNormal",i.DEFAULT_BIAS_INITIALIZER="zeros",e.verifyArgs(r),i.rank=n,zp(i.rank,"rank"),1!==i.rank&&2!==i.rank)throw new wp("Convolution layer for rank other than 1 or 2 ("+i.rank+") is not implemented yet.");if(i.kernelSize=fm(r.kernelSize,n,"kernelSize"),i.strides=fm(null==r.strides?1:r.strides,n,"strides"),i.padding=null==r.padding?"valid":r.padding,eh(i.padding),i.dataFormat=null==r.dataFormat?"channelsLast":r.dataFormat,th(i.dataFormat),i.activation=tm(r.activation),i.useBias=null==r.useBias||r.useBias,i.biasInitializer=Jh(r.biasInitializer||i.DEFAULT_BIAS_INITIALIZER),i.biasConstraint=Kp(r.biasConstraint),i.biasRegularizer=am(r.biasRegularizer),i.activityRegularizer=am(r.activityRegularizer),i.dilationRate=fm(null==r.dilationRate?1:r.dilationRate,n,"dilationRate"),1===i.rank&&Array.isArray(i.dilationRate)&&1!==i.dilationRate.length)throw new bp("dilationRate must be a number or an array of a single number for 1D convolution, but received "+JSON.stringify(i.dilationRate));if(2===i.rank)if("number"==typeof i.dilationRate)i.dilationRate=[i.dilationRate,i.dilationRate];else if(2!==i.dilationRate.length)throw new bp("dilationRate must be a number or array of two numbers for 2D convolution, but received "+JSON.stringify(i.dilationRate));return i}return ip(e,t),e.verifyArgs=function(t){if(Sp("kernelSize"in t,"required key 'kernelSize' not in config"),"number"!=typeof t.kernelSize&&!Fp(t.kernelSize,"number",1,2))throw new bp("BaseConv expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.prototype.getConfig=function(){var e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Zd(this.activation),useBias:this.useBias,biasInitializer:Yh(this.biasInitializer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),biasConstraint:Gp(this.biasConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(df),vm=function(t){function e(n,r){var i=t.call(this,n,r)||this;return i.kernel=null,e.verifyArgs(r),i.filters=r.filters,zp(i.filters,"filters"),i.kernelInitializer=Jh(r.kernelInitializer||i.DEFAULT_KERNEL_INITIALIZER),i.kernelConstraint=Kp(r.kernelConstraint),i.kernelRegularizer=am(r.kernelRegularizer),i}return ip(e,t),e.prototype.build=function(t){var e;t=nf(t);var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new bp("The channel dimension of the input should be defined. Found "+t[n]);var r=t[n],i=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:(e={},e[n]=r,e)}],this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){var e;t=ef(t);var r=null==n.bias?null:n.bias.read();if(1===n.rank)e=function(t,e,n,r,i,o,a){return void 0===r&&(r=1),void 0===i&&(i="valid"),void 0===a&&(a=1),Gt(function(){if(null==o&&(o="channelsLast"),th(o),3!==t.shape.length)throw new bp("The input of a conv1dWithBias operation should be 3, but is "+t.shape.length+" instead.");if(3!==e.shape.length)throw new bp("The kernel for a conv1dWithBias operation should be 3, but is "+e.shape.length+" instead");if(null!=n&&1!==n.shape.length)throw new bp("The bias for a conv1dWithBias operation should be 1, but is "+e.shape.length+" instead");if("channelsFirst"===o&&(t=Gu(t,[0,2,1])),"causal"===i)throw new wp("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var s=vs(t,e,r,"same"===i?"same":"valid","NWC",a);return null!=n&&(s=kh(s,n)),s})}(t,n.kernel.read(),r,n.strides[0],n.padding,n.dataFormat,n.dilationRate[0]);else if(2===n.rank)e=function(t,e,n,r,i,o,a){return void 0===r&&(r=[1,1]),void 0===i&&(i="valid"),Gt(function(){if(null==o&&(o="channelsLast"),th(o),3!==t.rank&&4!==t.rank)throw new bp("conv2dWithBias expects input to be of rank 3 or 4, but received "+t.rank+".");if(3!==e.rank&&4!==e.rank)throw new bp("conv2dWithBias expects kernel to be of rank 3 or 4, but received "+t.rank+".");var s=gm(t,o);if("causal"===i)throw new wp("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return s=bs(s,e,r,"same"===i?"same":"valid","NHWC",a),null!=n&&(s=kh(s,n)),"channelsFirst"===o&&(s=Gu(s,[0,3,1,2])),s})}(t,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate);else if(3===n.rank)throw new wp("3D convolution is not implemented yet.");return null!=n.activation&&(e=n.activation.apply(e)),e})},e.prototype.computeOutputShape=function(t){t=nf(t);for(var e=[],n="channelsLast"===this.dataFormat?t.slice(1,t.length-1):t.slice(2),r=0;r<n.length;++r){var i=dm(n[r],this.kernelSize[r],this.padding,this.strides[r],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[r]);e.push(i)}var o=[t[0]];return"channelsLast"===this.dataFormat?(o=o.concat(e)).push(this.filters):(o.push(this.filters),o=o.concat(e)),o},e.prototype.getConfig=function(){var e={filters:this.filters,kernelInitializer:Yh(this.kernelInitializer),kernelRegularizer:im(this.kernelRegularizer),kernelConstraint:Gp(this.kernelConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.verifyArgs=function(t){if(!("filters"in t)||"number"!=typeof t.filters||t.filters<1)throw new bp("Convolution layer expected config.filters to be a 'number' > 0 but got "+JSON.stringify(t.filters))},e}(ym),bm=function(t){function e(n){var r=t.call(this,2,n)||this;return e.verifyArgs(n),r}return ip(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!Fp(t.kernelSize,"number",1,2))throw new bp("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(vm);zc.registerClass(bm);var wm=function(t){function e(e){var n=t.call(this,e)||this;if(n.inputSpec=[new lf({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new bp("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return ip(e,t),e.prototype.build=function(t){var e;if(4!==(t=nf(t)).length)throw new bp("Input should have rank 4; Received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new bp("The channel dimension of the inputs should be defined. Found `None`.");var r=t[n],i=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new lf({ndim:4,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){var e=ef(t);if(4!==e.shape.length)throw new bp("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+e.shape.length);var r,i,o=e.shape,a=o[0];"channelsFirst"===n.dataFormat?(r=2,i=3):(r=1,i=2);var s=o[r],u=o[i],l=n.kernelSize[0],c=n.kernelSize[1],p=n.strides[0],h=n.strides[1],f=[a,mm(s,p,l,n.padding),mm(u,h,c,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(e=Gu(e,[0,2,3,1]));var d=Cs(e,n.kernel.read(),f,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(d=Gu(d,[0,3,1,2])),null!=n.bias&&(d=kh(d,n.bias.read(),n.dataFormat)),null!=n.activation&&(d=n.activation.apply(d)),d})},e.prototype.computeOutputShape=function(t){var e,n,r,i=(t=nf(t)).slice();"channelsFirst"===this.dataFormat?(e=1,n=2,r=3):(e=3,n=1,r=2);var o=this.kernelSize[0],a=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return i[e]=this.filters,i[n]=mm(i[n],s,o,this.padding),i[r]=mm(i[r],u,a,this.padding),i},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.dilationRate,e},e.className="Conv2DTranspose",e}(bm);zc.registerClass(wm);var xm=function(t){function e(e){return t.call(this,2,e)||this}return ip(e,t),e.className="SeparableConv2D",e}(function(t){function e(e,n){var r=t.call(this,e,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new bp("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new bp("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=n.padding&&"same"!==n.padding&&"valid"!==n.padding)throw new bp("SeparableConv"+r.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(n.padding));return r.depthMultiplier=null==n.depthMultiplier?1:n.depthMultiplier,r.depthwiseInitializer=Jh(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=am(n.depthwiseRegularizer),r.depthwiseConstraint=Kp(n.depthwiseConstraint),r.pointwiseInitializer=Jh(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=am(n.pointwiseRegularizer),r.pointwiseConstraint=Kp(n.pointwiseConstraint),r}return ip(e,t),e.prototype.build=function(t){var e;if((t=nf(t)).length<this.rank+2)throw new bp("Inputs to SeparableConv"+this.rank+"D should have rank "+(this.rank+2)+", but received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n]||t[n]<0)throw new bp("The channel dimension of the inputs should be defined, but found "+JSON.stringify(t[n]));for(var r=t[n],i=this.kernelSize.concat([r,this.depthMultiplier]),o=[],a=0;a<this.rank;++a)o.push(1);o.push(r*this.depthMultiplier,this.filters),this.depthwiseKernel=this.addWeight("depthwise_kernel",i,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",o,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,!0,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.inputSpec=[new lf({ndim:this.rank+2,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){var e;if(t=ef(t),1===n.rank)throw new wp("1D separable convolution is not implemented yet.");return 2===n.rank&&("channelsFirst"===n.dataFormat&&(t=Gu(t,[0,2,3,1])),e=Ss(t,n.depthwiseKernel.read(),n.pointwiseKernel.read(),n.strides,n.padding,n.dilationRate,"NHWC")),n.useBias&&(e=kh(e,n.bias.read(),n.dataFormat)),null!=n.activation&&(e=n.activation.apply(e)),"channelsFirst"===n.dataFormat&&(e=Gu(e,[0,3,1,2])),e})},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Yh(this.depthwiseInitializer),e.pointwiseInitializer=Yh(this.pointwiseInitializer),e.depthwiseRegularizer=im(this.depthwiseRegularizer),e.pointwiseRegularizer=im(this.pointwiseRegularizer),e.depthwiseConstraint=Gp(this.depthwiseConstraint),e.pointwiseConstraint=Gp(this.pointwiseConstraint),e},e.className="SeparableConv",e}(vm));zc.registerClass(xm);var Nm=function(t){function e(n){var r=t.call(this,1,n)||this;return e.verifyArgs(n),r.inputSpec=[{ndim:3}],r}return ip(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,delete e.dataFormat,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!Fp(t.kernelSize,"number",1,1))throw new bp("Conv1D expects config.kernelSize to be number or number[] with length 1, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv1D",e}(vm);zc.registerClass(Nm);var Sm=function(t){function e(e){var n=t.call(this,e)||this;return"number"==typeof e.cropping?n.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?n.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:n.cropping=e.cropping,n.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,n.inputSpec=[{ndim:4}],n}return ip(e,t),e.prototype.computeOutputShape=function(t){return"channelsFirst"===this.dataFormat?[t[0],t[1],t[2]-this.cropping[0][0]-this.cropping[0][1],t[3]-this.cropping[1][0]-this.cropping[1][1]]:[t[0],t[1]-this.cropping[0][0]-this.cropping[0][1],t[2]-this.cropping[1][0]-this.cropping[1][1],t[3]]},e.prototype.call=function(t,e){var n=this;return Gt(function(){return t=ef(t),"channelsLast"===n.dataFormat?bh(bh(t,n.cropping[0][0],t.shape[1]-n.cropping[0][0]-n.cropping[0][1],2),n.cropping[1][0],t.shape[2]-n.cropping[1][1]-n.cropping[1][0],3):bh(bh(t,n.cropping[0][0],t.shape[2]-n.cropping[0][0]-n.cropping[0][1],3),n.cropping[1][0],t.shape[3]-n.cropping[1][1]-n.cropping[1][0],4)})},e.prototype.getConfig=function(){var e={cropping:this.cropping,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Cropping2D",e}(df);zc.registerClass(Sm);var Cm=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_SIZE=[2,2],n.inputSpec=[{ndim:4}],n.size=null==e.size?n.DEFAULT_SIZE:e.size,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,n}return ip(e,t),e.prototype.computeOutputShape=function(t){if("channelsFirst"===this.dataFormat){var e=null==t[2]?null:this.size[0]*t[2],n=null==t[3]?null:this.size[1]*t[3];return[t[0],t[1],e,n]}return e=null==t[1]?null:this.size[0]*t[1],n=null==t[2]?null:this.size[1]*t[2],[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return Gt(function(){var e=ef(t),r=e.shape;if("channelsFirst"===n.dataFormat){e=Gu(e,[0,2,3,1]);var i=n.size[0]*r[2],o=n.size[1]*r[3],a=e.resizeNearestNeighbor([i,o]);return Gu(a,[0,3,1,2])}return i=n.size[0]*r[1],o=n.size[1]*r[2],e.resizeNearestNeighbor([i,o])})},e.prototype.getConfig=function(){var e={size:this.size,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="UpSampling2D",e}(df);zc.registerClass(Cm);var Em=function(t){function e(e){var n=t.call(this,2,e)||this;return n.depthwiseKernel=null,n.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,n.depthwiseInitializer=Jh(e.depthwiseInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.depthwiseConstraint=Kp(e.depthwiseConstraint),n.depthwiseRegularizer=am(e.depthwiseRegularizer),n}return ip(e,t),e.prototype.build=function(t){if((t=nf(t)).length<4)throw new bp("Inputs to DepthwiseConv2D should have rank 4. Received input shape: "+JSON.stringify(t)+".");var e="channelsFirst"===this.dataFormat?1:3;if(null==t[e]||t[e]<0)throw new bp("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not ("+t[e]+").");var n=t[e],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){var e=function(t,e,n,r,i,o){return void 0===n&&(n=[1,1]),void 0===r&&(r="valid"),Gt(function(){null==i&&(i="channelsLast"),th(i);var a=gm(t,i);if(4!==t.rank)throw new bp("Input for depthwiseConv2d is required to be 4-D, but is instead "+t.rank+"-D");if(4!==e.rank)throw new bp("depthwiseKernel is required to be 4-D, but is instead "+e.rank+"-D");return a=Ns(a,e,n,"same"===r?"same":"valid","NHWC",o),"channelsFirst"===i&&(a=Gu(a,[0,3,1,2])),a})}(t=ef(t),n.depthwiseKernel.read(),n.strides,n.padding,n.dataFormat,null);return n.useBias&&(e=kh(e,n.bias.read(),n.dataFormat)),null!=n.activation&&(e=n.activation.apply(e)),e})},e.prototype.computeOutputShape=function(t){t=nf(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2],r="channelsFirst"===this.dataFormat?t[1]*this.depthMultiplier:t[3]*this.depthMultiplier,i=dm(e,this.kernelSize[0],this.padding,this.strides[0]),o=dm(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[t[0],r,i,o]:[t[0],i,o,r]},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Yh(this.depthwiseInitializer),e.depthwiseRegularizer=im(this.depthwiseRegularizer),e.depthwiseConstraint=Gp(this.depthwiseRegularizer),e},e.className="DepthwiseConv2D",e}(ym);zc.registerClass(Em);var Im=function(t){function e(e){var n=t.call(this,e)||this;if(n.rate=Math.max(Math.min(e.rate,1),0),n.rateScalar=gp(n.rate),n.noiseShape=e.noiseShape,n.seed=e.seed,null!=n.seed)throw new wp("Non-default seed is not implemented in Dropout layer yet: "+n.seed);return n.supportsMasking=!0,n}return ip(e,t),e.prototype.getNoiseShape=function(t){if(null==this.noiseShape)return this.noiseShape;for(var e=t.shape,n=[],r=0;r<this.noiseShape.length;++r)n.push(null==this.noiseShape[r]?e[r]:this.noiseShape[r]);return n},e.prototype.call=function(t,e){var n=this;return Gt(function(){n.invokeCallHook(t,e);var r=ef(t);if(null!=n.noiseShape&&!X.arraysEqual(r.shape,n.noiseShape))throw new wp("Non-default noise shape is not implemented in Dropout layer yet: "+JSON.stringify(n.noiseShape));if(0<n.rate&&n.rate<1){var i=null!=e.training&&e.training,o=n.getNoiseShape(r);return Th(function(){return Ah(r,n.rateScalar,o,n.seed)},function(){return r},i)}return t})},e.prototype.getConfig=function(){var e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.prototype.dispose=function(){var e=t.prototype.dispose.call(this);return this.rateScalar.isDisposed||(this.rateScalar.dispose(),e.numDisposedVariables++),e},e.className="Dropout",e}(df);zc.registerClass(Im);var km=function(t){function e(e){var n=t.call(this,e)||this;if(n.activation=null,n.useBias=!0,n.kernel=null,n.bias=null,n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){var r=null;null!=e.batchSize&&(r=e.batchSize),n.batchInputShape=[r,e.inputDim]}return n.units=e.units,zp(n.units,"units"),n.activation=tm(e.activation),null!=e.useBias&&(n.useBias=e.useBias),n.kernelInitializer=Jh(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.biasInitializer=Jh(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelConstraint=Kp(e.kernelConstraint),n.biasConstraint=Kp(e.biasConstraint),n.kernelRegularizer=am(e.kernelRegularizer),n.biasRegularizer=am(e.biasRegularizer),n.activityRegularizer=am(e.activityRegularizer),n.supportsMasking=!0,n.inputSpec=[{minNDim:2}],n}return ip(e,t),e.prototype.build=function(t){var e,n=(t=nf(t))[t.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[n,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:(e={},e[-1]=n,e)}],this.built=!0},e.prototype.computeOutputShape=function(t){var e=(t=nf(t)).slice();return e[e.length-1]=this.units,e},e.prototype.call=function(t,e){var n=this;return Gt(function(){n.invokeCallHook(t,e);var r=Ch(ef(t),n.kernel.read());return null!=n.bias&&(r=kh(r,n.bias.read())),null!=n.activation&&(r=n.activation.apply(r)),r})},e.prototype.getConfig=function(){var e={units:this.units,activation:Zd(this.activation),useBias:this.useBias,kernelInitializer:Yh(this.kernelInitializer),biasInitializer:Yh(this.biasInitializer),kernelRegularizer:im(this.kernelRegularizer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),kernelConstraint:Gp(this.kernelConstraint),biasConstraint:Gp(this.biasConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dense",e}(df);zc.registerClass(km);var Am=function(t){function e(e){var n=t.call(this,e||{})||this;return n.inputSpec=[{minNDim:3}],n}return ip(e,t),e.prototype.computeOutputShape=function(t){for(var e=0,n=(t=nf(t)).slice(1);e<n.length;e++)if(null==n[e])throw new bp('The shape of the input to "Flatten" is not fully defined (got '+t.slice(1)+'). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.');return[t[0],ch(t,1)]},e.prototype.call=function(t,e){var n=this;return Gt(function(){return n.invokeCallHook(t,e),function(t){if(t.rank<=1)throw new bp("batchFlatten requires a minimum rank of 2. Got rank: "+t.rank+".");var e=[t.shape[0],ch(t.shape,1)];return t.reshape(e)}(ef(t))})},e.className="Flatten",e}(df);zc.registerClass(Am);var Tm=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.activation=tm(e.activation),n}return ip(e,t),e.prototype.call=function(t,e){var n=this;return Gt(function(){n.invokeCallHook(t,e);var r=ef(t);return n.activation.apply(r)})},e.prototype.getConfig=function(){var e={activation:Zd(this.activation)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Activation",e}(df);zc.registerClass(Tm);var Rm=function(t){function e(e){var n=t.call(this,e)||this;return n.n=e.n,n.inputSpec=[{ndim:2}],n}return ip(e,t),e.prototype.computeOutputShape=function(t){return[t[0],this.n,t[1]]},e.prototype.call=function(t,e){var n=this;return Gt(function(){return function(t,e){return Gt(function(){if(2!==t.shape.length)throw new bp("repeat() expects a rank-2 tensor, but received a rank-"+t.shape.length+" tensor.");return Nh(gh(t,1),[1,e,1])})}(t=ef(t),n.n)})},e.prototype.getConfig=function(){var e={n:this.n},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="RepeatVector",e}(df);zc.registerClass(Rm);var Dm=function(t){function e(e){var n=t.call(this,e)||this;n.targetShape=e.targetShape;for(var r=0;r<n.targetShape.length;++r)n.isUnknown(n.targetShape[r])&&(n.targetShape[r]=null);return n}return ip(e,t),e.prototype.isUnknown=function(t){return t<0||null==t},e.prototype.fixUnknownDimension=function(t,e){for(var n="Total size of new array must be unchanged.",r=e.slice(),i=1,o=null,a=0;a<r.length;++a){var s=r[a];if(this.isUnknown(s)){if(null!==o)throw new bp("Can only specifiy one unknown dimension.");o=a}else i*=s}var u=ch(t);if(null!==o){if(0===i||u%i!=0)throw new bp(n);r[o]=u/i}else if(u!==i)throw new bp(n);return r},e.prototype.computeOutputShape=function(t){for(var e=!1,n=0;n<t.length;++n)if(this.isUnknown(t[n])){e=!0;break}return e?t.slice(0,1).concat(this.targetShape):t.slice(0,1).concat(this.fixUnknownDimension(t.slice(1),this.targetShape))},e.prototype.call=function(t,e){var n=this;return Gt(function(){n.invokeCallHook(t,e);var r=ef(t),i=r.shape,o=i.slice(0,1).concat(n.fixUnknownDimension(i.slice(1),n.targetShape));return r.reshape(o)})},e.prototype.getConfig=function(){var e={targetShape:this.targetShape},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Reshape",e}(df);zc.registerClass(Dm);var Om=function(t){function e(e){var n=t.call(this,e)||this;if(null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error("Permute constructor requires `dims` to be an Array, but received "+e.dims+" instead.");var r=dh(1,e.dims.length+1);if(!X.arraysEqual(e.dims.slice().sort(),r))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");return n.dims=e.dims,n.dimsIncludingBatch=[0].concat(n.dims),n.inputSpec=[new lf({ndim:n.dims.length+1})],n}return ip(e,t),e.prototype.computeOutputShape=function(t){var e=(t=nf(t)).slice();return this.dims.forEach(function(n,r){e[r+1]=t[n]}),e},e.prototype.call=function(t,e){return Gu(ef(t),this.dimsIncludingBatch)},e.prototype.getConfig=function(){var e={dims:this.dims},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Permute",e}(df);zc.registerClass(Om);var _m=function(t){function e(e){var n=t.call(this,e)||this;if(n.embeddings=null,n.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){var r=null;null!=e.batchSize&&(r=e.batchSize),null==e.inputLength?n.batchInputShape=[r,null]:n.batchInputShape=[r].concat(Ip(e.inputLength))}return n.inputDim=e.inputDim,zp(n.inputDim,"inputDim"),n.outputDim=e.outputDim,zp(n.outputDim,"outputDim"),n.embeddingsInitializer=Jh(e.embeddingsInitializer||n.DEFAULT_EMBEDDINGS_INITIALIZER),n.embeddingsRegularizer=am(e.embeddingsRegularizer),n.activityRegularizer=am(e.activityRegularizer),n.embeddingsConstraint=Kp(e.embeddingsConstraint),n.maskZero=e.maskZero,n.supportsMasking=e.maskZero,n.inputLength=e.inputLength,n}return ip(e,t),e.prototype.build=function(t){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0},e.prototype.warnOnIncompatibleInputShape=function(t){},e.prototype.computeMask=function(t,e){var n=this;return Gt(function(){return n.maskZero?(t=ef(t),pu(t,qe(t))):null})},e.prototype.computeOutputShape=function(t){if(t=nf(t),null==this.inputLength)return t.concat([this.outputDim]);var e=Ip(this.inputLength);if(e.length!==t.length-1)throw new bp('"inputLength" is '+this.inputLength+", but received input shape has shape "+t);for(var n=0,r=0;r<e.length;++r){var i=e[r],o=t[r+1];if(null!=i&&null!=o&&i!==o)throw new bp('"inputLength" is '+this.inputLength+", but received input shape has shape "+t);null==i&&(e[n]=o),n++}return[t[0]].concat(e,[this.outputDim])},e.prototype.call=function(t,e){var n=this;return Gt(function(){n.invokeCallHook(t,e);var r=ef(t);return"int32"!==r.dtype&&(r=mh(r,"int32")),Eh(n.embeddings.read(),r.as1D()).reshape(nf(n.computeOutputShape(r.shape)))})},e.prototype.getConfig=function(){var e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Yh(this.embeddingsInitializer),embeddingsRegularizer:im(this.embeddingsRegularizer),activityRegularizer:im(this.activityRegularizer),embeddingsConstraint:Gp(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Embedding",e}(df);zc.registerClass(_m);var Mm=function(t){function e(e){var n=t.call(this,e||{})||this;return n.supportsMasking=!0,n}return ip(e,t),e.prototype.mergeFunction=function(t){throw new wp},e.prototype.computeElementwiseOpOutputShape=function(t,e){if(null==t||null==e)return null;if(t.length<e.length)return this.computeElementwiseOpOutputShape(e,t);if(0===e.length)return t;for(var n=t.slice(0,t.length-e.length),r=0;r<e.length;++r){var i=t[t.length-e.length+r],o=e[r];if(null==i||null==o||i<0||o<0)n.push(null);else if(1===i)n.push(o);else if(1===o)n.push(i);else{if(i!==o)throw new bp("Operands could not be broadcast together with shapes "+JSON.stringify(t)+" "+JSON.stringify(e));n.push(i)}}return n},e.prototype.build=function(t){if(Array.isArray(t)&&!Array.isArray(t[0])&&(t=[nf(t)]),(t=t).length<2)throw new bp("A merge layer should be called on an Array of at least 2 inputs. Got "+t.length+" input(s).");for(var e=[],n=0,r=t;n<r.length;n++)null!=(a=r[n])&&null!==a[0]&&e.push(a[0]);if((e=_p(e)).length>1)throw new bp("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(t)+".");for(var i=null==t[0]?null:t[0].slice(1),o=1;o<t.length;++o){var a=null==t[o]?null:t[o].slice(1);i=this.computeElementwiseOpOutputShape(i,a)}var s=t.map(function(t){return t.length});-1===t.indexOf(null)&&1===_p(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){if(t=t,n.reshapeRequired){var e=[],r=t.map(function(t){return t.rank});if(-1===r.indexOf(null)){for(var i=fh(r),o=0,a=t;o<a.length;o++){for(var s=(h=a[o]).rank,u=0;u<i-s;++u)h=gh(h,1);e.push(h)}return n.mergeFunction(e)}for(var l=!1,c=0,p=t;c<p.length;c++){var h;if(null==(s=(h=p[c]).rank)){var f=h.shape,d=f[0],m=f.slice(1).concat([d]),g=h.reshape([d].concat(ch(f.slice(1))));g=(g=Gu(g,[1,0])).reshape(m),e.push(g),l=!0}else if(s>1){var y=dh(1,s).concat([0]);e.push(Gu(h,y)),l=!0}else e.push(h)}var v=n.mergeFunction(e),b=v.rank;if(l)if(null==b){var w=v.shape;m=[d=w[w.length-1]].concat(w.slice(0,w.length-1)),v=Gu(v.reshape([-1,d]),[1,0]).reshape(m)}else b>1&&(y=[b-1].concat(dh(0,b-1)),v=Gu(v,y));return v}return n.mergeFunction(t)})},e.prototype.computeOutputShape=function(t){var e;e=null==(t=t)[0]?null:t[0].slice(1);for(var n=1;n<t.length;++n){var r=null==t[n]?null:t[n].slice(1);e=this.computeElementwiseOpOutputShape(e,r)}for(var i=[],o=0,a=t;o<a.length;o++)null!=(r=a[o])&&null!==r[0]&&i.push(r[0]);return 1===(i=_p(i)).length?i.concat(e):[null].concat(e)},e.prototype.computeMask=function(t,e){return Gt(function(){if(null==e)return null;if(!Array.isArray(e))throw new bp("`mask` should be an Array");if(!Array.isArray(t))throw new bp("`inputs` should be an Array");if(e.length!==t.length)throw new bp("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths ("+t.length+" vs "+e.length+")");if(e.every(function(t){return null==t}))return null;for(var n=(e=e.map(function(t){return null==t?t:Go(t,0)}))[0],r=1;r<e.length-1;++r)n=Mu(n,e[r]);return n})},e}(df),Lm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.mergeFunction=function(t){return Gt(function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=fu(e,t[n]);return e})},e.className="Add",e}(Mm);zc.registerClass(Lm);var Fm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.mergeFunction=function(t){return Gt(function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=Iu(e,t[n]);return e})},e.className="Multiply",e}(Mm);zc.registerClass(Fm);var zm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.mergeFunction=function(t){return Gt(function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=fu(e,t[n]);return Iu(gp(1/t.length),e)})},e.className="Average",e}(Mm);zc.registerClass(zm);var Pm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.mergeFunction=function(t){return Gt(function(){for(var e=t[0],n=1;n<t.length;++n)e=wu(e,t[n]);return e})},e.className="Maximum",e}(Mm);zc.registerClass(Pm);var Bm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.mergeFunction=function(t){return Gt(function(){for(var e=t[0],n=1;n<t.length;++n)e=Nu(e,t[n]);return e})},e.className="Minimum",e}(Mm);zc.registerClass(Bm);var Um=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_AXIS=-1,null==e&&(e={}),n.axis=null==e.axis?n.DEFAULT_AXIS:e.axis,n.supportsMasking=!0,n.reshapeRequired=!1,n}return ip(e,t),e.prototype.build=function(t){if(!Array.isArray(t)||!Array.isArray(t[0])||1===t.length)throw new bp("A `Concatenate` layer should be called on a list of at least 2 inputs");for(var e=!0,n=0,r=t=t;n<r.length;n++)if(null!=(c=r[n])){e=!1;break}if(!e){for(var i=[],o=0;o<t.length;++o){var a=t[o].slice();a.splice(this.axis,1);for(var s=!1,u=0,l=i;u<l.length;u++){var c=l[u];if(X.arraysEqual(c,a)){s=!0;break}}s||i.push(a)}if(i.length>1)throw new bp("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}},e.prototype.mergeFunction=function(t){var e=this;return Gt(function(){return wh(t,e.axis)})},e.prototype.computeOutputShape=function(t){if(!Array.isArray(t)||!Array.isArray(t[0]))throw new bp("A `Concatenate` layer should be called on a list of inputs.");for(var e=t,n=e[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,i=0,o=e.slice(1);i<o.length;i++){var a=o[i];if(null==n[r]||null==a[r]){n[r]=null;break}n[r]+=a[r]}return n},e.prototype.computeMask=function(t,e){var n=this;if(null==e)return null;if(!Array.isArray(e))throw new bp("`mask` should be an array for Concatenate");if(!Array.isArray(t))throw new bp("`inputs` should be an array for Concatenate");if(e.length!==t.length)throw new bp("Mismatch in the length of mask ("+e.length+") and the legnth of inputs ("+t.length+")");return Gt(function(){var r=!0;if(e.forEach(function(t){null==t||(r=!1)}),r)return null;for(var i=[],o=0;o<t.length;++o)null==e[o]?i.push(je(t[o]).asType("bool")):e[o].rank<t[o].rank?i.push(Go(e[o],-1)):i.push(e[o]);var a=No(i,n.axis);return qs(a,-1,!1)})},e.prototype.getConfig=function(){var e={axis:this.axis},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Concatenate",e}(Mm);function Wm(t,e){for(;t<0;)t+=e;return t}zc.registerClass(Um);var Vm=function(t){function e(e){var n=t.call(this,e)||this;return n.axes=e.axes,n.normalize=null!=e.normalize&&e.normalize,n.supportsMasking=!0,n.reshapeRequired=!1,n}return ip(e,t),e.prototype.build=function(t){X.assert(Array.isArray(t)&&2===t.length&&Array.isArray(t[0])&&Array.isArray(t[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var e=t[0],n=t[1];if(e.length>3||n.length>3)throw new wp("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);if(e[r[0]]!==n[r[1]])throw new bp("Dimension incompatibility: "+e[r[0]]+" !== "+n[r[1]])},e.prototype.mergeFunction=function(t){if(2!==t.length)throw new bp("A `Dot` layer must be called on exactly 2 inputs, but received "+t.length+" input(s).");var e,n=t[0],r=t[1];return e=Array.isArray(this.axes)?this.axes.map(function(e,n){return Wm(e,t[n].shape.length)}):[Wm(this.axes,n.shape.length),Wm(this.axes,r.shape.length)],this.normalize&&(n=Tf(n,e[0]),r=Tf(r,e[1])),function(t,e,n){if(t.shape.length>3||e.shape.length>3)throw new wp("batchDot is not implemented for tensors of 4D or higher rank yet");if(X.assert(t.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, but got "+t.shape.length}),X.assert(t.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, but got "+e.shape.length}),"number"==typeof n&&(n=[n,n]),"complex64"===t.dtype||"complex64"===e.dtype)throw new wp("batchDot is not implemented for complex64-type Tensors yet.");var r=t.shape.length,i=e.shape.length;null==n&&(n=[r-1,i-2]);var o=n;return Gt(function(){var n,a;if(r>i){n=r-i;for(var s=[],u=0;u<n;++u)s.push(1);e=e.reshape(e.shape.concat(s))}else if(i>r){for(n=i-r,s=[],u=0;u<n;++u)s.push(1);t=t.reshape(t.shape.concat(s))}else n=0;if(2===t.shape.length&&2===e.shape.length)a=o[0]===o[1]?t.mulStrict(e).sum(o[0]):t.transpose([1,0]).mulStrict(e).sum(o[1]);else{var l=o[0]!==t.shape.length-1,c=o[1]===e.shape.length-1;a=t.matMul(e,l,c)}if(n>0){var p,h=[];for(u=p=r>i?r+i-3:r-1;u<p+n;++u)h.push(u);a=a.squeeze(h)}return 1===a.shape.length&&(a=a.expandDims(1)),a})}(n,r,e)},e.prototype.interpretAxes=function(t,e){return Array.isArray(this.axes)?this.axes:[Wm(this.axes,t.length),Wm(this.axes,e.length)]},e.prototype.computeOutputShape=function(t){X.assert(Array.isArray(t)&&2===t.length&&Array.isArray(t[0])&&Array.isArray(t[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var e=t[0].slice(),n=t[1].slice();if(e.length>3||n.length>3)throw new wp("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);e.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);var i=e.concat(n);return 1===i.length&&i.push(1),i},e.prototype.computeMask=function(t,e){return null},e.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dot",e}(Mm);function jm(t,e,n,r,i,o){var a;if(void 0===o&&(o=.001),2===t.rank)a=rs(t,e,n,r,i,o);else if(3===t.rank)a=is(t,e,n,r,i,o);else{if(4!==t.rank)throw new wp("batchNormalization is not implemented for array of rank "+t.rank+" yet");a=os(t,e,n,r,i,o)}return a}function qm(t,e,n,r,i){return void 0===i&&(i=.001),X.arraysEqual(r.slice().sort(),dh(0,t.rank-1))?function(t,e,n,r,i){return void 0===i&&(i=.001),Gt(function(){var o=Zs(t,r),a=o.mean,s=o.variance;return[jm(t,a,s,n,e,i),a,s]})}(t,e,n,r,i):function(t,e,n,r,i){return void 0===i&&(i=.001),Gt(function(){for(var o=Zs(t,r),a=o.mean,s=o.variance,u=[],l=0,c=dh(0,t.rank);l<c.length;l++){var p=c[l];-1!==r.indexOf(p)?u.push(1):u.push(t.shape[p])}var h=a.reshape(u),f=s.reshape(u),d=null==e?null:e.reshape(u),m=null==n?null:n.reshape(u);return[jm(t,h,f,m,d,i),a,s]})}(t,e,n,r,i)}zc.registerClass(Vm);var Gm=function(t){function e(e){var n=this;return null==e&&(e={}),(n=t.call(this,e)||this).supportsMasking=!0,n.axis=null==e.axis?-1:e.axis,n.momentum=null==e.momentum?.99:e.momentum,n.epsilon=null==e.epsilon?.001:e.epsilon,n.center=null==e.center||e.center,n.scale=null==e.scale||e.scale,n.betaInitializer=Jh(e.betaInitializer||"zeros"),n.gammaInitializer=Jh(e.gammaInitializer||"ones"),n.movingMeanInitializer=Jh(e.movingMeanInitializer||"zeros"),n.movingVarianceInitializer=Jh(e.movingVarianceInitializer||"ones"),n.betaConstraint=Kp(e.betaConstraint),n.gammaConstraint=Kp(e.gammaConstraint),n.betaRegularizer=am(e.betaRegularizer),n.gammaRegularizer=am(e.gammaRegularizer),n}return ip(e,t),e.prototype.build=function(t){var e;t=nf(t);var n=this.axis>=0?this.axis:this.axis+t.length,r=t[n];if(null==r)throw new bp("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(t)+".");this.inputSpec=[new lf({ndim:t.length,axes:(e={},e[n]=r,e)})];var i=[r];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){var r=null!=e.training&&e.training,i=ef(t),o=i.shape,a=o.length,s=dh(0,a),u=n.axis>=0?n.axis:n.axis+a;s.splice(u,1);var l=Np(1,a);l[u]=o[u];var c=s.slice();c.sort();var p=!X.arraysEqual(c,dh(0,a).slice(0,a-1));if(!r)return function(){if(p){var t=n.movingMean.read().reshape(l),e=n.movingVariance.read().reshape(l),r=n.center?n.beta.read().reshape(l):null,o=n.scale?n.gamma.read().reshape(l):null;return jm(i,t,e,r,o,n.epsilon)}return jm(i,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon)}();var h=qm(i,n.gamma.read(),n.beta.read(),s,n.epsilon),f=h[0],d=h[1],m=h[2],g=function(t,e,n){Gt(function(){var r=gp(1).sub(gp(n)),i=t.read(),o=i.sub(e).mul(r);t.write(i.sub(o))})};return g(n.movingMean,d,n.momentum),g(n.movingVariance,m,n.momentum),f})},e.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Yh(this.betaInitializer),gammaInitializer:Yh(this.gammaInitializer),movingMeanInitializer:Yh(this.movingMeanInitializer),movingVarianceInitializer:Yh(this.movingVarianceInitializer),betaRegularizer:im(this.betaRegularizer),gammaRegularizer:im(this.gammaRegularizer),betaConstraint:Gp(this.betaConstraint),gammaConstraint:Gp(this.gammaConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="BatchNormalization",e}(df);zc.registerClass(Gm);var Hm=function(t){function e(e){var n=this;if(null==e&&(e={}),(n=t.call(this,e)||this).dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)n.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new bp("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+e.padding.length+" array.");var r=void 0,i=void 0;if("number"==typeof e.padding[0])r=[e.padding[0],e.padding[0]],i=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new bp("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+e.padding[0].length+" array.");if(r=e.padding[0],2!==e.padding[1].length)throw new bp("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+e.padding[1].length+" array.");i=e.padding[1]}n.padding=[r,i]}return n.inputSpec=[new lf({ndim:4})],n}return ip(e,t),e.prototype.computeOutputShape=function(t){var e,n;return t=nf(t),"channelsFirst"===this.dataFormat?(e=null!=t[2]&&t[2]>=0?t[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[3]&&t[3]>=0?t[3]+this.padding[1][0]+this.padding[1][1]:null,[t[0],t[1],e,n]):(e=null!=t[1]&&t[1]>=0?t[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[2]&&t[2]>=0?t[2]+this.padding[1][0]+this.padding[1][1]:null,[t[0],e,n,t[3]])},e.prototype.call=function(t,e){var n=this;return Gt(function(){return function(t,e,n){return Gt(function(){if(4!==t.rank)throw new bp("temporalPadding expects input tensor to be 4-D, but received a "+t.rank+"-D tensor.");if(null==e&&(e=[[1,1],[1,1]]),2!==e.length||2!==e[0].length||2!==e[1].length)throw new bp("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new bp("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r="channelsFirst"===n?[[0,0],[0,0],e[0],e[1]]:[[0,0],e[0],e[1],[0,0]],Xo(t,r)})}(ef(t),n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ZeroPadding2D",e}(df);function Km(t,e,n,r,i,o){return Gt(function(){var a;th(i),function(t){Lp(Jp,"PoolMode",t)}(o),eh(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==i&&(i="channelsLast"),null==o&&(o="max"),t=gm(t,i);var s="same"===r?"same":"valid";return a="max"===o?Ls(t,e,n,s):Fs(t,e,n,s),"channelsFirst"===i&&(a=Gu(a,[0,3,1,2])),a})}zc.registerClass(Hm);var $m=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=2),n=t.call(this,e)||this,"number"==typeof e.poolSize)n.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new bp("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.poolSize));n.poolSize=e.poolSize}if(zp(n.poolSize,"poolSize"),null==e.strides)n.strides=n.poolSize;else if("number"==typeof e.strides)n.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new bp("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.strides));n.strides=e.strides}return zp(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,eh(n.padding),n.inputSpec=[new lf({ndim:3})],n}return ip(e,t),e.prototype.computeOutputShape=function(t){var e=dm((t=nf(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]},e.prototype.call=function(t,e){var n=this;return Gt(function(){n.invokeCallHook(t,e),t=gh(ef(t),2);var r=n.poolingFunction(ef(t),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return oa(r,[2])})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(df),Xm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return th(i),eh(r),Km(t,e,n,r,i,"max")},e.className="MaxPooling1D",e}($m);zc.registerClass(Xm);var Ym=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return th(i),eh(r),Km(t,e,n,r,i,"avg")},e.className="AveragePooling1D",e}($m);zc.registerClass(Ym);var Jm=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=[2,2]),(n=t.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)n.strides=n.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new bp("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+e.strides.length+".");n.strides=e.strides}else n.strides=[e.strides,e.strides];return zp(n.poolSize,"poolSize"),zp(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,th(n.dataFormat),eh(n.padding),n.inputSpec=[new lf({ndim:4})],n}return ip(e,t),e.prototype.computeOutputShape=function(t){t=nf(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2];return e=dm(e,this.poolSize[0],this.padding,this.strides[0]),n=dm(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n]:[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return Gt(function(){return n.invokeCallHook(t,e),n.poolingFunction(ef(t),n.poolSize,n.strides,n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(df),Zm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return th(i),eh(r),Km(t,e,n,r,i,"max")},e.className="MaxPooling2D",e}(Jm);zc.registerClass(Zm);var Qm=function(t){function e(e){return t.call(this,e)||this}return ip(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return th(i),eh(r),Km(t,e,n,r,i,"avg")},e.className="AveragePooling2D",e}(Jm);zc.registerClass(Qm);var tg=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[new lf({ndim:3})],n}return ip(e,t),e.prototype.computeOutputShape=function(t){return[t[0],t[2]]},e.prototype.call=function(t,e){throw new wp},e}(df),eg=function(t){function e(e){return t.call(this,e||{})||this}return ip(e,t),e.prototype.call=function(t,e){return Gt(function(){var e=ef(t);return Ys(e,1)})},e.className="GlobalAveragePooling1D",e}(tg);zc.registerClass(eg);var ng=function(t){function e(e){return t.call(this,e||{})||this}return ip(e,t),e.prototype.call=function(t,e){return Gt(function(){var e=ef(t);return Xs(e,1)})},e.className="GlobalMaxPooling1D",e}(tg);zc.registerClass(ng);var rg=function(t){function e(e){var n=t.call(this,e)||this;return n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,th(n.dataFormat),n.inputSpec=[new lf({ndim:4})],n}return ip(e,t),e.prototype.computeOutputShape=function(t){return t=t,"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]},e.prototype.call=function(t,e){throw new wp},e.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(df),ig=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.call=function(t,e){var n=this;return Gt(function(){var e=ef(t);return"channelsLast"===n.dataFormat?Ys(e,[1,2]):Ys(e,[2,3])})},e.className="GlobalAveragePooling2D",e}(rg);zc.registerClass(ig);var og=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.call=function(t,e){var n=this;return Gt(function(){var e=ef(t);return"channelsLast"===n.dataFormat?Xs(e,[1,2]):Xs(e,[2,3])})},e.className="GlobalMaxPooling2D",e}(rg);function ag(t,e,n,r){if(Array.isArray(t)){if(null!=e||null!=n)throw new bp("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=t.slice(t.length-r,t.length),t=t.slice(0,t.length-r)),t.length>1&&(e=t.slice(1,t.length)),t=t[0]}function i(t){return null==t||Array.isArray(t)?t:[t]}return{inputs:t,initialState:e=i(e),constants:n=i(n)}}function sg(t,e,n,r,i,o,a,s){return void 0===r&&(r=!1),void 0===a&&(a=!1),void 0===s&&(s=!1),Gt(function(){var u=e.shape.length;if(u<3)throw new bp("Input should be at least 3D, but is "+u+"D.");var l=[1,0].concat(dh(2,u));if(e=Gu(e,l),null!=o)throw new wp("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=i&&((i=i.asType("bool").asType("float32")).rank===u-1&&(i=Go(i,-1)),i=Gu(i,l)),r&&(e=As(e,0),null!=i&&(i=As(i,0)));var c,p,h=[],f=n,d=e.shape[0],m=la(e);null!=i&&(p=la(i));for(var g,y=function(e){var n=m[e],r=Gt(function(){return t(n,f)});if(null==i)c=r[0],f=r[1];else{var o=Gt(function(){var t=p[e],n=je(t).sub(t);return{output:r[0].mul(t).addStrict(f[0].mul(n)),newStates:f.map(function(e,i){return r[1][i].mul(t).addStrict(e.mul(n))})}});c=o.output,f=o.newStates}s&&h.push(c)},v=0;v<d;++v)y(v);return s&&(g=aa(h,1)),[c,g,f]})}zc.registerClass(og);var ug=function(t){function e(e){var n,r=t.call(this,e)||this;if(null==e.cell)throw new bp("cell property is missing for the constructor of RNN.");if(null==(n=Array.isArray(e.cell)?new gg({cells:e.cell}):e.cell).stateSize)throw new bp("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return r.cell=n,r.returnSequences=null!=e.returnSequences&&e.returnSequences,r.returnState=null!=e.returnState&&e.returnState,r.goBackwards=null!=e.goBackwards&&e.goBackwards,r._stateful=null!=e.stateful&&e.stateful,r.unroll=null!=e.unroll&&e.unroll,r.supportsMasking=!0,r.inputSpec=[new lf({ndim:3})],r.stateSpec=null,r.states_=null,r.numConstants=null,r.keptStates=[],r}return ip(e,t),e.prototype.getStates=function(){return null==this.states_?dh(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(function(t){return null}):this.states_},e.prototype.setStates=function(t){this.states_=t},e.prototype.computeOutputShape=function(t){Qh(t)&&(t=t[0]),t=t;var e=this.cell.stateSize;Array.isArray(e)||(e=[e]);var n,r=e[0];if(n=this.returnSequences?[t[0],t[1],r]:[t[0],r],this.returnState){for(var i=[],o=0,a=e;o<a.length;o++){var s=a[o];i.push([t[0],s])}return[n].concat(i)}return n},e.prototype.computeMask=function(t,e){var n=this;return Gt(function(){Array.isArray(e)&&(e=e[0]);var t=n.returnSequences?e:null;if(n.returnState){var r=n.states.map(function(t){return null});return[t].concat(r)}return t})},Object.defineProperty(e.prototype,"states",{get:function(){if(null==this.states_){for(var t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[],n=0;n<t;++n)e.push(null);return e}return this.states_},set:function(t){this.states_=t},enumerable:!0,configurable:!0}),e.prototype.build=function(t){if(null!=this.numConstants)throw new wp("Constants support is not implemented in RNN yet.");Qh(t)&&(t=t[0]),t=t;var e=this.stateful?t[0]:null,n=t[t.length-1];this.inputSpec[0]=new lf({shape:[e,null,n]});var r,i=[t[0]].concat(t.slice(2));if(this.cell.build(i),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!X.arraysEqual(this.stateSpec.map(function(t){return t.shape[t.shape.length-1]}),r))throw new bp("An initialState was passed that is not compatible with cell.stateSize. Received stateSpec="+this.stateSpec+"; However cell.stateSize is "+this.cell.stateSize)}else this.stateSpec=r.map(function(t){return new lf({shape:[null,t]})});this.stateful&&this.resetStates()},e.prototype.resetStates=function(t,e){var n=this;void 0===e&&(e=!1),Gt(function(){if(!n.stateful)throw new yp("Cannot call resetStates() on an RNN Layer that is not stateful.");var r=n.inputSpec[0].shape[0];if(null==r)throw new bp("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==n.states_)Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map(function(t){return Be([r,t])}):n.states_=[Be([r,n.cell.stateSize])];else if(null==t)Kt(n.states_),null!=n.keptStates&&(Kt(n.keptStates),n.keptStates=[]),Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map(function(t){return Be([r,t])}):n.states_[0]=Be([r,n.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==n.states_.length)throw new bp("Layer "+n.name+" expects "+n.states_.length+" state(s), but it received "+t.length+" state value(s). Input received: "+t);!0===e?n.keptStates.push(n.states_.slice()):Kt(n.states_);for(var i=0;i<n.states_.length;++i){var o=t[i],a=Array.isArray(n.cell.stateSize)?n.cell.stateSize[i]:n.cell.stateSize,s=[r,a];if(!X.arraysEqual(o.shape,s))throw new bp("State "+i+" is incompatible with layer "+n.name+": expected shape="+s+", received shape="+o.shape);n.states_[i]=o}}n.states_.forEach(function(t){return Ht(t)})})},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var o=ag(e,r,i,this.numConstants);e=o.inputs,r=o.initialState,i=o.constants;var a=[],s=[];if(null!=r){n.initialState=r,a=a.concat(r),this.stateSpec=[];for(var u=0,l=r;u<l.length;u++){var c=l[u];this.stateSpec.push(new lf({shape:c.shape}))}s=s.concat(this.stateSpec)}if(null!=i&&(n.constants=i,a=a.concat(i),this.numConstants=i.length),a[0]instanceof cf){var p=[e].concat(a),h=this.inputSpec.concat(s),f=this.inputSpec;this.inputSpec=h;var d=t.prototype.apply.call(this,p,n);return this.inputSpec=f,d}return t.prototype.apply.call(this,e,n)},e.prototype.call=function(t,e){var n=this;return Gt(function(){var r=null==e?null:e.mask,i=null==e?null:e.training,o=null==e?null:e.initialState;t=ef(t),null==o&&(o=n.stateful?n.states_:n.getInitialState(t));var a=Array.isArray(n.cell.stateSize)?n.cell.stateSize.length:1;if(o.length!==a)throw new bp("RNN Layer has "+a+" state(s) but was passed "+o.length+" initial state(s).");n.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var s={training:i},u=sg(function(t,e){var r=n.cell.call([t].concat(e),s);return[r[0],r.slice(1)]},t,o,n.goBackwards,r,null,n.unroll,n.returnSequences),l=u[0],c=u[1],p=u[2];n.stateful&&n.resetStates(p,i);var h=n.returnSequences?c:l;return n.returnState?[h].concat(p):h})},e.prototype.getInitialState=function(t){var e=this;return Gt(function(){var n=Be(t.shape);return n=gh(n=Qs(n,[1,2])),Array.isArray(e.cell.stateSize)?e.cell.stateSize.map(function(t){return t>1?Nh(n,[1,t]):n}):e.cell.stateSize>1?[Nh(n,[1,e.cell.stateSize])]:[n]})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(e.numConstants=this.numConstants);var n=this.cell.getConfig();e.cell={className:this.cell.getClassName(),config:n};var r=t.prototype.getConfig.call(this);return Object.assign(e,r),e},e.className="RNN",e}(df);zc.registerClass(ug);var lg=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e}(df),cg=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,zp(n.units,"units"),n.activation=tm(null==e.activation?n.DEFAULT_ACTIVATION:e.activation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=Jh(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=Jh(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=Jh(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=am(e.kernelRegularizer),n.recurrentRegularizer=am(e.recurrentRegularizer),n.biasRegularizer=am(e.biasRegularizer),n.kernelConstraint=Kp(e.kernelConstraint),n.recurrentConstraint=Kp(e.recurrentConstraint),n.biasConstraint=Kp(e.biasConstraint),n.dropout=hh([1,fh([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=hh([1,fh([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return ip(e,t),e.prototype.build=function(t){t=nf(t),this.kernel=this.addWeight("kernel",[t[t.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){if(2!==(t=t).length)throw new bp("SimpleRNNCell expects 2 input Tensors, got "+t.length+".");var r=t[1];t=t[0];var i,o=null!=e.training&&e.training;0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=yg(function(){return je(t)},n.dropout,o)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=yg(function(){return je(r)},n.recurrentDropout,o));var a=n.dropoutMask,s=n.recurrentDropoutMask;i=Ch(null!=a?Iu(t,a):t,n.kernel.read()),null!=n.bias&&(i=kh(i,n.bias.read())),null!=s&&(r=Iu(r,s));var u=fu(i,Ch(r,n.recurrentKernel.read()));return null!=n.activation&&(u=n.activation.apply(u)),[u,u]})},e.prototype.getConfig=function(){var e={units:this.units,activation:Zd(this.activation),useBias:this.useBias,kernelInitializer:Yh(this.kernelInitializer),recurrentInitializer:Yh(this.recurrentInitializer),biasInitializer:Yh(this.biasInitializer),kernelRegularizer:im(this.kernelRegularizer),recurrentRegularizer:im(this.recurrentRegularizer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),kernelConstraint:Gp(this.kernelConstraint),recurrentConstraint:Gp(this.recurrentConstraint),biasConstraint:Gp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="SimpleRNNCell",e}(lg);zc.registerClass(cg);var pg=function(t){function e(e){return e.cell=new cg(e),t.call(this,e)||this}return ip(e,t),e.prototype.call=function(e,n){var r=this;return Gt(function(){null!=r.cell.dropoutMask&&(Kt(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Kt(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,o=null==n?null:n.training,a=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:i,training:o,initialState:a})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Zd(this.activation),useBias:this.useBias,kernelInitializer:Yh(this.kernelInitializer),recurrentInitializer:Yh(this.recurrentInitializer),biasInitializer:Yh(this.biasInitializer),kernelRegularizer:im(this.kernelRegularizer),recurrentRegularizer:im(this.recurrentRegularizer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),kernelConstraint:Gp(this.kernelConstraint),recurrentConstraint:Gp(this.recurrentConstraint),biasConstraint:Gp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.className="SimpleRNN",e}(ug);zc.registerClass(pg);var hg=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,zp(n.units,"units"),n.activation=tm(void 0===e.activation?n.DEFAULT_ACTIVATION:e.activation),n.recurrentActivation=tm(void 0===e.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=Jh(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=Jh(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=Jh(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=am(e.kernelRegularizer),n.recurrentRegularizer=am(e.recurrentRegularizer),n.biasRegularizer=am(e.biasRegularizer),n.kernelConstraint=Kp(e.kernelConstraint),n.recurrentConstraint=Kp(e.recurrentConstraint),n.biasConstraint=Kp(e.biasConstraint),n.dropout=hh([1,fh([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=hh([1,fh([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.implementation=e.implementation,n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return ip(e,t),e.prototype.build=function(t){var e=(t=nf(t))[t.length-1];this.kernel=this.addWeight("kernel",[e,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){if(2!==(t=t).length)throw new bp("GRUCell expects 2 input Tensors (inputs, h, c), got "+t.length+".");var r=null!=e.training&&e.training,i=t[1];t=t[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=yg(function(){return je(t)},n.dropout,r,3)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=yg(function(){return je(i)},n.recurrentDropout,r,3));var o,a,s,u=n.dropoutMask,l=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(t=Iu(t,u[0]));var c=Ch(t,n.kernel.read());n.useBias&&(c=kh(c,n.bias.read())),0<n.recurrentDropout&&n.recurrentDropout<1&&(i=Iu(i,l[0]));var p=n.recurrentKernel.read(),h=ko(p,[2*n.units,n.units],p.rank-1),f=h[0],d=h[1],m=Ch(i,f),g=ko(c,3,c.rank-1),y=g[0],v=g[1],b=g[2],w=ko(m,2,m.rank-1),x=w[0],N=w[1];o=n.recurrentActivation.apply(fu(y,x)),a=n.recurrentActivation.apply(fu(v,N));var S=Ch(Iu(a,i),d);s=n.activation.apply(fu(b,S));var C=fu(Iu(o,i),Iu(fu(gp(1),Oa(o)),s));return[C,C]})},e.prototype.getConfig=function(){var e={units:this.units,activation:Zd(this.activation),recurrentActivation:Zd(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Yh(this.kernelInitializer),recurrentInitializer:Yh(this.recurrentInitializer),biasInitializer:Yh(this.biasInitializer),kernelRegularizer:im(this.kernelRegularizer),recurrentRegularizer:im(this.recurrentRegularizer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),kernelConstraint:Gp(this.kernelConstraint),recurrentConstraint:Gp(this.recurrentConstraint),biasConstraint:Gp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="GRUCell",e}(lg);zc.registerClass(hg);var fg=function(t){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new hg(e),t.call(this,e)||this}return ip(e,t),e.prototype.call=function(e,n){var r=this;return Gt(function(){null!=r.cell.dropoutMask&&(Kt(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Kt(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,o=null==n?null:n.training,a=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:i,training:o,initialState:a})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Zd(this.activation),recurrentActivation:Zd(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Yh(this.kernelInitializer),recurrentInitializer:Yh(this.recurrentInitializer),biasInitializer:Yh(this.biasInitializer),kernelRegularizer:im(this.kernelRegularizer),recurrentRegularizer:im(this.recurrentRegularizer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),kernelConstraint:Gp(this.kernelConstraint),recurrentConstraint:Gp(this.recurrentConstraint),biasConstraint:Gp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},e.className="GRU",e}(ug);zc.registerClass(fg);var dg=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,zp(n.units,"units"),n.activation=tm(void 0===e.activation?n.DEFAULT_ACTIVATION:e.activation),n.recurrentActivation=tm(void 0===e.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=Jh(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=Jh(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=Jh(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.unitForgetBias=e.unitForgetBias,n.kernelRegularizer=am(e.kernelRegularizer),n.recurrentRegularizer=am(e.recurrentRegularizer),n.biasRegularizer=am(e.biasRegularizer),n.kernelConstraint=Kp(e.kernelConstraint),n.recurrentConstraint=Kp(e.recurrentConstraint),n.biasConstraint=Kp(e.biasConstraint),n.dropout=hh([1,fh([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=hh([1,fh([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.implementation=e.implementation,n.stateSize=[n.units,n.units],n.dropoutMask=null,n.recurrentDropoutMask=null,n}return ip(e,t),e.prototype.build=function(t){var e,n,r=(t=nf(t))[t.length-1];if(this.kernel=this.addWeight("kernel",[r,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var i=this.biasInitializer,o=this.units;n=new((e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ip(e,t),e.prototype.apply=function(t,e){var n=i.apply([o]),r=(new Mh).apply([o]),a=i.apply([2*o]);return xh(xh(n,r),a)},e}(Oh)).className="CustomInit",e)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},e.prototype.call=function(t,e){var n=this;return Gt(function(){var r=null!=e.training&&e.training;if(3!==(t=t).length)throw new bp("LSTMCell expects 3 input Tensors (inputs, h, c), got "+t.length+".");var i=t[1],o=t[2];t=t[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=yg(function(){return je(t)},n.dropout,r,4)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=yg(function(){return je(i)},n.recurrentDropout,r,4));var a,s,u,l,c=n.dropoutMask,p=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(t=Iu(t,c[0]));var h=Ch(t,n.kernel.read());0<n.recurrentDropout&&n.recurrentDropout<1&&(i=Iu(i,p[0])),h=fu(h,Ch(i,n.recurrentKernel.read())),n.useBias&&(h=kh(h,n.bias.read()));var f=ko(h,4,h.rank-1),d=f[0],m=f[1],g=f[2],y=f[3];a=n.recurrentActivation.apply(d),s=n.recurrentActivation.apply(m),u=fu(Iu(s,o),Iu(a,n.activation.apply(g))),l=n.recurrentActivation.apply(y);var v=Iu(l,n.activation.apply(u));return[v,v,u]})},e.prototype.getConfig=function(){var e={units:this.units,activation:Zd(this.activation),recurrentActivation:Zd(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Yh(this.kernelInitializer),recurrentInitializer:Yh(this.recurrentInitializer),biasInitializer:Yh(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:im(this.kernelRegularizer),recurrentRegularizer:im(this.recurrentRegularizer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),kernelConstraint:Gp(this.kernelConstraint),recurrentConstraint:Gp(this.recurrentConstraint),biasConstraint:Gp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LSTMCell",e}(lg);zc.registerClass(dg);var mg=function(t){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new dg(e),t.call(this,e)||this}return ip(e,t),e.prototype.call=function(e,n){var r=this;return Gt(function(){null!=r.cell.dropoutMask&&(Kt(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Kt(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,o=null==n?null:n.training,a=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:i,training:o,initialState:a})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"unitForgetBias",{get:function(){return this.cell.unitForgetBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Zd(this.activation),recurrentActivation:Zd(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Yh(this.kernelInitializer),recurrentInitializer:Yh(this.recurrentInitializer),biasInitializer:Yh(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:im(this.kernelRegularizer),recurrentRegularizer:im(this.recurrentRegularizer),biasRegularizer:im(this.biasRegularizer),activityRegularizer:im(this.activityRegularizer),kernelConstraint:Gp(this.kernelConstraint),recurrentConstraint:Gp(this.recurrentConstraint),biasConstraint:Gp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},e.className="LSTM",e}(ug);zc.registerClass(mg);var gg=function(t){function e(e){var n=t.call(this,e)||this;return n.cells=e.cells,n}return ip(e,t),Object.defineProperty(e.prototype,"stateSize",{get:function(){for(var t=[],e=0,n=this.cells.slice().reverse();e<n.length;e++){var r=n[e];Array.isArray(r.stateSize)?t.push.apply(t,r.stateSize):t.push(r.stateSize)}return t},enumerable:!0,configurable:!0}),e.prototype.call=function(t,e){var n=this;return Gt(function(){for(var r=(t=t).slice(1),i=[],o=0,a=n.cells.slice().reverse();o<a.length;o++){var s=a[o];Array.isArray(s.stateSize)?i.push(r.splice(0,s.stateSize.length)):i.push(r.splice(0,1))}i.reverse();for(var u,l=[],c=0;c<n.cells.length;++c)s=n.cells[c],r=i[c],u=0===c?[t[0]].concat(r):[u[0]].concat(r),u=s.call(u,e),l.push(u.slice(1));r=[];for(var p=0,h=l.slice().reverse();p<h.length;p++){var f=h[p];r.push.apply(r,f)}return[u[0]].concat(r)})},e.prototype.build=function(t){var e;Qh(t)&&(t=t[0]),t=t;for(var n=0,r=this.cells;n<r.length;n++){var i=r[n];i.build(t),e=Array.isArray(i.stateSize)?i.stateSize[0]:i.stateSize,t=[t[0],e]}this.built=!0},e.prototype.getConfig=function(){for(var e=[],n=0,r=this.cells;n<r.length;n++){var i=r[n];e.push({className:this.getClassName(),config:i.getConfig()})}var o={cells:e},a=t.prototype.getConfig.call(this);return Object.assign(o,a),o},e.fromConfig=function(t,e,n){void 0===n&&(n={});for(var r=[],i=0,o=e.cells;i<o.length;i++){var a=o[i];r.push(pd(a,n))}return new t({cells:r})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){if(!this.trainable)return[];for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.trainableWeights)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.nonTrainableWeights)}if(!this.trainable){for(var i=[],o=0,a=this.cells;o<a.length;o++)r=a[o],i.push.apply(i,r.trainableWeights);return i.concat(t)}return t},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.weights)}return sf(t)},e.prototype.setWeights=function(t){for(var e=[],n=0,r=this.cells;n<r.length;n++)for(var i=r[n],o=i.weights.length,a=t.splice(o),s=0;s<i.weights.length;++s)e.push([i.weights[s],a[s]]);uf(e)},e.className="StackedRNNCells",e}(lg);function yg(t,e,n,r){function i(){return Ah(t(),gp(e))}if(void 0===n&&(n=null),void 0===r&&(r=1),r>1){for(var o=[],a=0;a<r;a++)o.push(Th(i,t,n));return o.forEach(function(t){return Ht(t)}),o}return Ht(Th(i,t,n))}zc.registerClass(gg);var vg=function(t){function e(e){var n=t.call(this,e)||this;return n.layer=e.layer,n}return ip(e,t),e.prototype.build=function(t){this.built=!0},Object.defineProperty(e.prototype,"trainable",{get:function(){return null!=this.layer&&this.layer.trainable},set:function(t){null!=this.layer&&(this.layer.trainable=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.layer.getWeights()},e.prototype.setWeights=function(t){this.layer.setWeights(t)},e.prototype.getConfig=function(){var e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)},e.fromConfig=function(t,e,n){void 0===n&&(n={});var r=pd(e.layer,n);delete e.layer;var i={layer:r};return Object.assign(i,e),new t(i)},e}(df),bg=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n}return ip(e,t),e.prototype.build=function(e){if((e=nf(e)).length<3)throw new bp("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(e));this.inputSpec=[{shape:e}];var n=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),t.prototype.build.call(this,e)},e.prototype.computeOutputShape=function(t){var e=[(t=nf(t))[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),r=t[1];return[n[0],r].concat(n.slice(1))},e.prototype.call=function(t,e){var n=this;return Gt(function(){return sg(function(t,r){return[ef(n.layer.call(t,e)),[]]},t=ef(t),[],!1,null,null,!1,!0)[1]})},e.className="TimeDistributed",e}(vg);zc.registerClass(bg);var wg="concat",xg=function(t){function e(e){var n=t.call(this,e)||this,r=e.layer.getConfig(),i={};i.className=e.layer.getClassName(),i.config=r,n.forwardLayer=pd(i),r.goBackwards=!0!==r.goBackwards;var o={};if(o.className=e.layer.getClassName(),o.config=r,n.backwardLayer=pd(o),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===e.mergeMode?wg:e.mergeMode,function(t){Lp(Zp,"BidirectionalMergeMode",t)}(n.mergeMode),e.weights)throw new wp("weights support is not implemented for Bidirectional layer yet.");return n._stateful=e.layer.stateful,n.returnSequences=e.layer.returnSequences,n.returnState=e.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=e.layer.inputSpec,n.numConstants=null,n}return ip(e,t),Object.defineProperty(e.prototype,"trainable",{get:function(){return this._trainable},set:function(t){this._trainable=t,null!=this.forwardLayer&&(this.forwardLayer.trainable=t),null!=this.backwardLayer&&(this.backwardLayer.trainable=t)},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},e.prototype.setWeights=function(t){var e=t.length,n=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,n)),this.backwardLayer.setWeights(t.slice(n))},e.prototype.computeOutputShape=function(t){var e,n,r,i=this.forwardLayer.computeOutputShape(t);return Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i,this.returnState?(r=i.slice(1),e=i[0]):e=i[0],e=e,"concat"===this.mergeMode?(e[e.length-1]*=2,n=[e]):n=null==this.mergeMode?[e,e.slice()]:[e],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[e].concat(r).concat(r.slice()):Ep(n)},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var o=ag(e,r,i,this.numConstants);if(e=o.inputs,r=o.initialState,i=o.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(null==r||0===r.length)&&null==i)return t.prototype.apply.call(this,e,n);var a=[],s=[];if(null!=r){var u=r.length;if(u%2>0)throw new bp("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,a.push.apply(a,r);var l=r.map(function(t){return new lf({shape:t.shape})});this.forwardLayer.stateSpec=l.slice(0,u/2),this.backwardLayer.stateSpec=l.slice(u/2),s.push.apply(s,l)}if(null!=i)throw new wp("Support for constants in Bidirectional layers is not implemented yet.");for(var c=a[0]instanceof cf,p=0,h=a;p<h.length;p++)if(h[p]instanceof cf!==c)throw new bp("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){var f=[e].concat(a),d=this.inputSpec.concat(s),m=this.inputSpec;this.inputSpec=d;var g=t.prototype.apply.call(this,f,n);return this.inputSpec=m,g}return t.prototype.apply.call(this,e,n)},e.prototype.call=function(t,e){var n=this;return Gt(function(){if(null!=e.mask)throw new wp("The support for masking is not implemented for Bidirectional layers yet.");var r,i,o,a,s=e.initialState;if(null==s)r=n.forwardLayer.call(t,e),i=n.backwardLayer.call(t,e);else{var u=s.slice(0,s.length/2),l=s.slice(s.length/2);r=n.forwardLayer.call(t,Object.assign(e,{initialState:u})),i=n.backwardLayer.call(t,Object.assign(e,{initialState:l}))}return n.returnState&&(Array.isArray(r)&&(o=r.slice(1).concat(i.slice(1))),r=r[0],i=i[0]),n.returnSequences&&(i=As(i,1)),"concat"===n.mergeMode?a=wh([r,i]):"sum"===n.mergeMode?a=fu(r,i):"ave"===n.mergeMode?a=Iu(gp(.5),fu(r,i)):"mul"===n.mergeMode?a=Iu(r,i):null==n.mergeMode&&(a=[r,i]),n.returnState?null==n.mergeMode?a.concat(o):[a].concat(o):a})},e.prototype.resetStates=function(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()},e.prototype.build=function(t){var e=this;ih(this.forwardLayer.name,function(){e.forwardLayer.build(t)}),ih(this.backwardLayer.name,function(){e.backwardLayer.build(t)}),this.built=!0},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={mergeMode:this.mergeMode},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.fromConfig=function(t,e){var n=pd(e.layer);if(delete e.layer,null!=e.numConstants)throw new wp("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var r=e;return r.layer=n,new t(r)},e.className="Bidirectional",e}(vg);function Ng(t){return new Ym(t)}function Sg(t){return new Qm(t)}function Cg(t){return new ng(t)}function Eg(t){return new og(t)}function Ig(t){return new Xm(t)}function kg(t){return new Zm(t)}zc.registerClass(xg);var Ag=Cg,Tg=Eg,Rg=Ig,Dg=kg,Og=Object.freeze({inputLayer:function(t){return new gf(t)},elu:function(t){return new cm(t)},reLU:function(t){return new sm(t)},leakyReLU:function(t){return new um(t)},prelu:function(t){return new lm(t)},softmax:function(t){return new hm(t)},thresholdedReLU:function(t){return new pm(t)},conv1d:function(t){return new Nm(t)},conv2d:function(t){return new bm(t)},conv2dTranspose:function(t){return new wm(t)},separableConv2d:function(t){return new xm(t)},cropping2D:function(t){return new Sm(t)},upSampling2d:function(t){return new Cm(t)},depthwiseConv2d:function(t){return new Em(t)},activation:function(t){return new Tm(t)},dense:function(t){return new km(t)},dropout:function(t){return new Im(t)},flatten:function(t){return new Am(t)},repeatVector:function(t){return new Rm(t)},reshape:function(t){return new Dm(t)},permute:function(t){return new Om(t)},embedding:function(t){return new _m(t)},add:function(t){return new Lm(t)},average:function(t){return new zm(t)},concatenate:function(t){return new Um(t)},maximum:function(t){return new Pm(t)},minimum:function(t){return new Bm(t)},multiply:function(t){return new Fm(t)},dot:function(t){return new Vm(t)},batchNormalization:function(t){return new Gm(t)},zeroPadding2d:function(t){return new Hm(t)},averagePooling1d:Ng,avgPool1d:function(t){return Ng(t)},avgPooling1d:function(t){return Ng(t)},averagePooling2d:Sg,avgPool2d:function(t){return Sg(t)},avgPooling2d:function(t){return Sg(t)},globalAveragePooling1d:function(t){return new eg(t)},globalAveragePooling2d:function(t){return new ig(t)},globalMaxPooling1d:Cg,globalMaxPooling2d:Eg,maxPooling1d:Ig,maxPooling2d:kg,gru:function(t){return new fg(t)},gruCell:function(t){return new hg(t)},lstm:function(t){return new mg(t)},lstmCell:function(t){return new dg(t)},simpleRNN:function(t){return new pg(t)},simpleRNNCell:function(t){return new cg(t)},rnn:function(t){return new ug(t)},stackedRNNCells:function(t){return new gg(t)},bidirectional:function(t){return new xg(t)},timeDistributed:function(t){return new bg(t)},globalMaxPool1d:Ag,globalMaxPool2d:Tg,maxPool1d:Rg,maxPool2d:Dg,Layer:df,RNN:ug,RNNCell:lg,input:Bd});var _g=Object.freeze({binaryAccuracy:function(t,e){return Gf(t,e)},binaryCrossentropy:function(t,e){return Yf(t,e)},sparseCategoricalAccuracy:function(t,e){return Jf(t,e)},categoricalAccuracy:function(t,e){return Hf(t,e)},categoricalCrossentropy:function(t,e){return id(t,e)},precision:function(t,e){return $f(t,e)},recall:function(t,e){return Xf(t,e)},cosineProximity:function(t,e){return jf(t,e)},meanAbsoluteError:function(t,e){return Df(t,e)},meanAbsolutePercentageError:function(t,e){return Of(t,e)},MAPE:function(t,e){return Of(t,e)},mape:function(t,e){return Of(t,e)},meanSquaredError:function(t,e){return Rf(t,e)},MSE:function(t,e){return Rf(t,e)},mse:function(t,e){return Rf(t,e)}}),Mg=Object.freeze({modelFromJSON:function(t,e){return sp(this,void 0,void 0,function(){var n,r,i,o,a,s,u,l;return up(this,function(c){switch(c.label){case 0:return"modelTopology"in t||(t={modelTopology:t}),null!=(n=(t=t).modelTopology).model_config&&(n=n.model_config),r=fd(n),i=pd(r,e),null==t.weightsManifest?[3,2]:[4,Tc.loadWeights(t.weightsManifest,t.pathPrefix,i.weights.map(function(t){return t.originalName}))];case 1:for(o=c.sent(),a={},s=0,u=i.weights;s<u.length;s++)l=u[s],a[l.originalName]=o[l.originalName];i.loadWeights(a),Kt(o),c.label=2;case 2:return[2,i]}})})}});var Lg,Fg=Object.freeze({l1l2:function(t){return new nm(t)},l1:function(t){return function(t){return new nm({l1:null!=t?t.l1:null,l2:0})}(t)},l2:function(t){return function(t){return new nm({l2:null!=t?t.l2:null,l1:0})}(t)}}),zg=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.model=null,e}return ip(e,t),e.prototype.setModel=function(t){if(!(t instanceof Fd))throw new Error("model must be a LayersModel, not some other Container");this.model=t},e}(wf),Pg=function(){return(Pg=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function Bg(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})}function Ug(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=e.call(t,a)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function Wg(t,e,n,r){var i=e.inputParams[t];if(i&&void 0!==i.inputIndexStart){var o=i.inputIndexStart,a=0===i.inputIndexEnd?void 0:void 0===i.inputIndexEnd?o+1:i.inputIndexEnd;if("tensor"===i.type)return Vg(e.inputNames[i.inputIndexStart],n,r);if("tensors"===i.type)return e.inputNames.slice(o,a).map(function(t){return Vg(t,n,r)});var s=Array.prototype.slice.call(Vg(e.inputNames.slice(o)[0],n,r).dataSync());return"number"===i.type?s[0]:s}var u=e.attrParams[t];return u&&u.value}function Vg(t,e,n){var r=Gg(t),i=r[0],o=r[1],a=n.currentContextIds.find(function(t){return!!e[qg(i,t)]});return void 0!==a?e[qg(i,a)][o]:void 0}function jg(t,e){var n=Gg(t),r=n[0],i=n[1];return[qg(r,e&&e.currentContextId),i]}function qg(t,e){return e?t+"-"+e:t}function Gg(t){var e=t.lastIndexOf(":");return-1===e?[t,0]:[t.substring(0,e),Number(t.substring(e+1))]}function Hg(t,e){for(var n=[],r=0;r<t.length;r+=e)n.push(t.slice(r,r+e));return n}!function(t){!function(t){t[t.DT_INVALID=0]="DT_INVALID",t[t.DT_FLOAT=1]="DT_FLOAT",t[t.DT_DOUBLE=2]="DT_DOUBLE",t[t.DT_INT32=3]="DT_INT32",t[t.DT_UINT8=4]="DT_UINT8",t[t.DT_INT16=5]="DT_INT16",t[t.DT_INT8=6]="DT_INT8",t[t.DT_STRING=7]="DT_STRING",t[t.DT_COMPLEX64=8]="DT_COMPLEX64",t[t.DT_INT64=9]="DT_INT64",t[t.DT_BOOL=10]="DT_BOOL",t[t.DT_QINT8=11]="DT_QINT8",t[t.DT_QUINT8=12]="DT_QUINT8",t[t.DT_QINT32=13]="DT_QINT32",t[t.DT_BFLOAT16=14]="DT_BFLOAT16",t[t.DT_FLOAT_REF=101]="DT_FLOAT_REF",t[t.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",t[t.DT_INT32_REF=103]="DT_INT32_REF",t[t.DT_UINT8_REF=104]="DT_UINT8_REF",t[t.DT_INT16_REF=105]="DT_INT16_REF",t[t.DT_INT8_REF=106]="DT_INT8_REF",t[t.DT_STRING_REF=107]="DT_STRING_REF",t[t.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",t[t.DT_INT64_REF=109]="DT_INT64_REF",t[t.DT_BOOL_REF=110]="DT_BOOL_REF",t[t.DT_QINT8_REF=111]="DT_QINT8_REF",t[t.DT_QUINT8_REF=112]="DT_QUINT8_REF",t[t.DT_QINT32_REF=113]="DT_QINT32_REF",t[t.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"}(t.DataType||(t.DataType={})),function(t){!function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(t.CheckpointFormatVersion||(t.CheckpointFormatVersion={}))}(t.SaverDef||(t.SaverDef={}))}(Lg||(Lg={}));var Kg=Object.freeze({json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),$g=Object.freeze({json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),Xg=Object.freeze({json:[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"}]}]}),Yg=Object.freeze({json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]}]}),Jg=Object.freeze({json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]}]}),Zg=Object.freeze({json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),Qg=Object.freeze({json:[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]}]}),ty=Object.freeze({json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]}),ey=Object.freeze({json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}]}),ny=Object.freeze({json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),ry=Object.freeze({json:[{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),iy=Object.freeze({json:[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}]}),oy=Object.freeze({json:[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]}]}),ay=Object.freeze({json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}]}),sy=Object.freeze({json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]}),uy=Object.freeze({json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]}]}),ly=["Switch","Merge","Enter","Exit","NextIteration"],cy=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"],py=function(){function t(){var t=[Kg,$g,Xg,Yg,Jg,Zg,Qg,ny,ey,ty,ry,iy,oy,ay,sy,uy],e=[].concat.apply([],t.map(function(t){return t.json}));this.opMappers=e.reduce(function(t,e){return t[e.tfOpName]=e,t},{})}return Object.defineProperty(t,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),t.prototype.isControlFlow=function(t){return ly.some(function(e){return e===t.op})},t.prototype.isDynamicShape=function(t){return cy.some(function(e){return e===t.op})},t.prototype.transformGraph=function(t){var e=this,n=!1,r=!1,i=[],o=[],a=t.node.reduce(function(t,a){return t[a.name]=e.mapNode(a),e.isControlFlow(a)&&(n=!0),e.isDynamicShape(a)&&(r=!0),"Placeholder"===a.op&&i.push(t[a.name]),"Const"===a.op&&o.push(t[a.name]),t},{}),s=[],u=[];return Object.keys(a).forEach(function(t){var e=a[t];e.inputNames.forEach(function(t){var n=jg(t)[0];e.inputs.push(a[n]),a[n].children.push(e)}),0===e.inputs.length&&s.push(e)}),Object.keys(a).forEach(function(t){var e=a[t];0===e.children.length&&u.push(e)}),{nodes:a,inputs:s,outputs:u,weights:o,placeholders:i,withControlFlow:n,withDynamicShape:r}},t.prototype.mapNode=function(t){var e=this,n=this.opMappers[t.op];if(void 0===n)throw new Error("Tensorflow Op is not supported: "+t.op);var r={name:t.name,op:t.op,category:n.category,inputNames:(t.input||[]).map(function(t){return t.startsWith("^")?t.substr(1):t}),inputs:[],children:[],inputParams:{},attrParams:{}};return null==t.attr&&(t.attr={}),null!=n.inputs&&(r.inputParams=n.inputs.reduce(function(t,e){return t[e.name]={type:e.type,inputIndexStart:e.start,inputIndexEnd:e.end},t},{})),null!=n.attrs&&(r.attrParams=n.attrs.reduce(function(n,r){var i=r.type,o=void 0;switch(r.type){case"string":void 0===(o=e.getStringParam(t.attr,r.tfName,r.defaultValue))&&r.tfDeprecatedName&&(o=e.getStringParam(t.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":void 0===(o=e.getNumberParam(t.attr,r.tfName,r.defaultValue||0))&&r.tfDeprecatedName&&(o=e.getNumberParam(t.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":void 0===(o=e.getNumericArrayParam(t.attr,r.tfName,r.defaultValue))&&r.tfDeprecatedName&&(o=e.getNumericArrayParam(t.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":void 0===(o=e.getBoolParam(t.attr,r.tfName,r.defaultValue))&&r.tfDeprecatedName&&(o=e.getBoolParam(t.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":void 0===(o=e.getTensorShapeParam(t.attr,r.tfName,r.defaultValue))&&r.tfDeprecatedName&&(o=e.getTensorShapeParam(t.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":void 0===(o=e.getDtypeParam(t.attr,r.tfName,r.defaultValue))&&r.tfDeprecatedName&&(o=e.getDtypeParam(t.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+r.type+" for op: "+t.op)}return n[r.name]={value:o,type:i},n},{})),r},t.prototype.decodeBase64=function(t){if("undefined"!=typeof atob)return atob(t);if("undefined"!=typeof Buffer)return new Buffer(t,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")},t.prototype.getStringParam=function(t,e,n,r){void 0===r&&(r=!1);var i=t[e];if(void 0!==i){var o=Array.isArray(i.s)?String.fromCharCode.apply(null,i.s):this.decodeBase64(i.s);return r?o:o.toLowerCase()}return n},t.prototype.getBoolParam=function(t,e,n){var r=t[e];return r?r.b:n},t.prototype.getNumberParam=function(t,e,n){var r=t[e]||{},i=r.i?r.i:r.f?r.f:n;return"number"==typeof i?i:parseInt(i,10)},t.prototype.getDtypeParam=function(t,e,n){var r=t[e];if(r&&r.type){var i=r.type;switch("string"==typeof r.type&&(i=Lg.DataType[r.type]),i){case Lg.DataType.DT_FLOAT:return"float32";case Lg.DataType.DT_INT32:return"int32";case Lg.DataType.DT_BOOL:return"bool";default:return n}}return n},t.prototype.getTensorShapeParam=function(t,e,n){var r=t[e];if(r&&r.shape){if(r.shape.unknownRank)return;if(null!=r.shape.dim)return r.shape.dim.map(function(t){return"number"==typeof t.size?t.size:parseInt(t.size,10)})}return n},t.prototype.getNumericArrayParam=function(t,e,n){var r=t[e];return r?(r.list.f&&r.list.f.length?r.list.f:r.list.i).map(function(t){return"number"==typeof t?t:parseInt(t,10)}):n},t}(),hy=function(t,e,n){switch(t.op){case"BiasAdd":case"Add":return[fu(Wg("a",t,e,n),Wg("b",t,e,n))];case"AddN":return[du(Wg("tensors",t,e,n))];case"FloorMod":case"Mod":return[Cu(Wg("a",t,e,n),Wg("b",t,e,n))];case"Mul":return[Iu(Wg("a",t,e,n),Wg("b",t,e,n))];case"RealDiv":case"Div":return[yu(Wg("a",t,e,n),Wg("b",t,e,n))];case"FloorDiv":return[bu(Wg("a",t,e,n),Wg("b",t,e,n))];case"Sub":return[Ou(Wg("a",t,e,n),Wg("b",t,e,n))];case"Minimum":return[Nu(Wg("a",t,e,n),Wg("b",t,e,n))];case"Maximum":return[wu(Wg("a",t,e,n),Wg("b",t,e,n))];case"Pow":return[Au(Wg("a",t,e,n),Wg("b",t,e,n))];case"SquaredDifference":return[Ru(Wg("a",t,e,n),Wg("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},fy=function(t,e,n){switch(t.op){case"Abs":return[da(Wg("x",t,e,n))];case"Acos":return[ma(Wg("x",t,e,n))];case"Acosh":return[ga(Wg("x",t,e,n))];case"Asin":return[ya(Wg("x",t,e,n))];case"Asinh":return[va(Wg("x",t,e,n))];case"Atan":return[ba(Wg("x",t,e,n))];case"Atan2":return[gu(Wg("x",t,e,n),Wg("y",t,e,n))];case"Atanh":return[wa(Wg("x",t,e,n))];case"Ceil":return[xa(Wg("x",t,e,n))];case"Cos":return[Sa(Wg("x",t,e,n))];case"Cosh":return[Ca(Wg("x",t,e,n))];case"Elu":return[Uu(Wg("x",t,e,n))];case"Erf":return[Ea(Wg("x",t,e,n))];case"Exp":return[Ia(Wg("x",t,e,n))];case"Expm1":return[ka(Wg("x",t,e,n))];case"Floor":return[Aa(Wg("x",t,e,n))];case"Log":return[Ta(Wg("x",t,e,n))];case"Log1p":return[Ra(Wg("x",t,e,n))];case"Neg":return[Oa(Wg("x",t,e,n))];case"Reciprocal":return[_a(Wg("x",t,e,n))];case"Relu":return[ju(Wg("x",t,e,n))];case"Round":return[Ma(Wg("x",t,e,n))];case"Selu":return[qu(Wg("x",t,e,n))];case"Sigmoid":return[Fa(Wg("x",t,e,n))];case"Sin":return[Pa(Wg("x",t,e,n))];case"Sign":return[za(Wg("x",t,e,n))];case"Sinh":return[Ba(Wg("x",t,e,n))];case"Softplus":return[Ua(Wg("x",t,e,n))];case"Sqrt":return[Wa(Wg("x",t,e,n))];case"Square":return[Va(Wg("x",t,e,n))];case"Tanh":return[Ga(Wg("x",t,e,n))];case"Tan":return[qa(Wg("x",t,e,n))];case"Relu6":case"ClipByValue":return[Na(Wg("x",t,e,n),Wg("clipValueMin",t,e,n),Wg("clipValueMax",t,e,n))];case"Rsqrt":return[La(Vg(t.inputNames[0],e,n))];case"Prod":return[tu(Wg("x",t,e,n),Wg("axes",t,e,n))];case"LeakyRelu":return[Wu(Wg("x",t,e,n),Wg("alpha",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},dy=function(){function t(e,n,r,i,o,a,s){this.name=e,this.dtype=n,this.maxSize=r,this.elementShape=i,this.identicalElementShapes=o,this.dynamicSize=a,this.clearAfterRead=s,this.tensors=[],this.closed_=!1,this.id=t.nextId++}return Object.defineProperty(t.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),t.prototype.clearAndClose=function(){this.tensors.forEach(function(t){return t.tensor.dispose()}),this.tensors=[],this.closed_=!0},t.prototype.size=function(){return this.tensors.length},t.prototype.read=function(t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||t>=this.tensors.length)throw new Error("Tried to read from index "+t+", but array size is: "+this.tensors.length);var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},t.prototype.readMany=function(t){var e=this;return t.map(function(t){return e.read(t)})},t.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var n=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+",\n          because the value dtype is "+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=e.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),n&&n.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(n&&n.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");n.tensor=e,n.written=!0,this.tensors[t]=n},t.prototype.writeMany=function(t,e){var n=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+t.length+" is not the same as tensors size: "+e.length+".");t.forEach(function(t,r){return n.write(t,e[r])})},t.prototype.gather=function(t,e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(!t){t=[];for(var n=0;n<this.size();n++)t.push(n)}if(0===t.length)return Re([],[0].concat(this.elementShape));var r=this.readMany(t);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),aa(r,0)},t.prototype.concat=function(t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+t);if(0===this.size())return Re([],[0].concat(this.elementShape));for(var e=[],n=0;n<this.size();n++)e.push(n);var r=this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+r[0].shape+")"),No(r,0)},t.prototype.scatter=function(t,e){if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);if(t.length!==e.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+t.length+" vs. "+e.shape[0]);var n=Math.max.apply(Math,t);if(!this.dynamicSize&&n>=this.maxSize)throw new Error("Max index must be < array size ("+n+"  vs. "+this.maxSize+")");this.writeMany(t,la(e,0))},t.prototype.split=function(t,e){var n=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,i=t.map(function(t){return r+=t});if(r!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        "+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var o=0===r?0:e.size/r,a=[];Gt(function(){e=e.reshape([1,r,o]);for(var s=0;s<t.length;++s){var u=[0,0===s?0:i[s-1],0],l=[1,t[s],o];a[s]=Ps(e,u,l).reshape(n.elementShape)}return a});for(var s=[],u=0;u<t.length;u++)s[u]=u;this.writeMany(s,a)},t.prototype.assertShapesMatchAllowUndefinedSize=function(t,e,n){void 0===n&&(n=""),X.assert(this.shapesEqualAllowUndefinedSize(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})},t.prototype.shapesEqualAllowUndefinedSize=function(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(-1!==t[n]&&-1!==e[n]&&t[n]!==e[n])return!1;return!0},t.nextId=0,t}();var my=function(t,e,n){switch(t.op){case"Conv1D":var r=Wg("stride",t,e,n),i=Wg("pad",t,e,n),o=Wg("dataFormat",t,e,n).toUpperCase(),a=Wg("dilation",t,e,n);return[vs(Wg("x",t,e,n),Wg("filter",t,e,n),r,i,o,a)];case"Conv2D":r=Wg("strides",t,e,n),i=Wg("pad",t,e,n),o=Wg("dataFormat",t,e,n).toUpperCase();var s=Wg("dilations",t,e,n);return[bs(Wg("x",t,e,n),Wg("filter",t,e,n),[r[1],r[2]],i,o,[s[0],s[1]])];case"Conv2DBackpropInput":case"Conv2dTranspose":var u=Wg("outputShape",t,e,n);return r=Wg("strides",t,e,n),i=Wg("pad",t,e,n),[Cs(Wg("x",t,e,n),Wg("filter",t,e,n),u,[r[1],r[2]],i)];case"DepthwiseConv2dNative":case"DepthwiseConv2d":return r=Wg("strides",t,e,n),i=Wg("pad",t,e,n),s=Wg("dilations",t,e,n),o=Wg("dataFormat",t,e,n).toUpperCase(),[Ns(Wg("input",t,e,n),Wg("filter",t,e,n),[r[1],r[2]],i,o,[s[0],s[1]])];case"AvgPool":r=Wg("strides",t,e,n),i=Wg("pad",t,e,n);var l=Wg("kernelSize",t,e,n);return[Fs(Wg("x",t,e,n),[l[1],l[2]],[r[1],r[2]],i)];case"MaxPool":return r=Wg("strides",t,e,n),i=Wg("pad",t,e,n),l=Wg("kernelSize",t,e,n),[Ls(Wg("x",t,e,n),[l[1],l[2]],[r[1],r[2]],i)];default:throw TypeError("Node type "+t.op+" is not implemented")}},gy=function(t,e,n){switch(t.op){case"Fill":var r=Wg("shape",t,e,n),i=Wg("dtype",t,e,n);return[Ue(r,Wg("value",t,e,n),i)];case"LinSpace":var o=Wg("start",t,e,n);return[We(o,Wg("stop",t,e,n),Wg("num",t,e,n))];case"OneHot":var a=Wg("indices",t,e,n),s=Wg("depth",t,e,n),u=Wg("onValue",t,e,n),l=Wg("offValue",t,e,n);return[$o(a,s,u,l)];case"Ones":return[Pe(Wg("shape",t,e,n),Wg("dtype",t,e,n))];case"OnesLike":return[je(Wg("x",t,e,n))];case"RandomUniform":return[na(Wg("shape",t,e,n),Wg("minval",t,e,n),Wg("maxval",t,e,n),Wg("dtype",t,e,n))];case"Range":return[Ve(o=Wg("start",t,e,n),Wg("stop",t,e,n),Wg("step",t,e,n),Wg("dtype",t,e,n))];case"TruncatedNormal":r=Wg("shape",t,e,n);var c=Wg("mean",t,e,n),p=Wg("stdDev",t,e,n),h=Wg("seed",t,e,n);return[ua(r,c,p,Wg("dtype",t,e,n),h)];case"Zeros":return[Be(Wg("shape",t,e,n),Wg("dtype",t,e,n))];case"ZerosLike":return[qe(Wg("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}};var yy=function(t,e,n){switch(t.op){case"TopKV2":var r=Wg("x",t,e,n),i=Wg("k",t,e,n),o=Wg("sorted",t,e,n),a=nl(r,i,o);return[a.values,a.indices];default:throw TypeError("Node type "+t.op+" is not implemented")}},vy=function(t,e,n){switch(t.op){case"Const":return e[t.name];case"PlaceholderWithDefault":var r=Wg("default",t,e,n);return[Vg(t.name,e,n)||r];case"Placeholder":return[Vg(t.name,e,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[Wg("x",t,e,n).clone()];case"IdentityN":return Wg("x",t,e,n).map(function(t){return t.clone()});case"Snapshot":return[Wg("x",t,e,n).clone()];case"Shape":return[Oe(Wg("x",t,e,n).shape,"int32")];case"ShapeN":return Wg("x",t,e,n).map(function(t){return Oe(t.shape)});case"Size":return[De(Wg("x",t,e,n).size,"int32")];case"Rank":return[De(Wg("x",t,e,n).rank,"int32")];case"NoOp":return[];case"Print":var i=Wg("x",t,e,n),o=Wg("data",t,e,n),a=Wg("message",t,e,n),s=Wg("summarize",t,e,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(a);for(var u=0;u<o.length;u++)console.log(Array.prototype.slice.call(o[u].dataSync()).slice(0,s));return[i];default:throw TypeError("Node type "+t.op+" is not implemented")}},by=function(t,e,n){switch(t.op){case"ResizeBilinear":var r=Wg("images",t,e,n),i=Wg("size",t,e,n),o=Wg("alignCorners",t,e,n);return[Dl.resizeBilinear(r,[i[0],i[1]],o)];case"ResizeNearestNeighbor":return r=Wg("images",t,e,n),i=Wg("size",t,e,n),o=Wg("alignCorners",t,e,n),[Dl.resizeNearestNeighbor(r,[i[0],i[1]],o)];case"CropAndResize":var a=Wg("image",t,e,n),s=Wg("boxes",t,e,n),u=Wg("boxInd",t,e,n),l=Wg("cropSize",t,e,n),c=Wg("method",t,e,n),p=Wg("extrapolationValue",t,e,n);return[Dl.cropAndResize(a,s,u,l,c,p)];default:throw TypeError("Node type "+t.op+" is not implemented")}},wy=function(t,e,n){switch(t.op){case"Equal":return[eu(Wg("a",t,e,n),Wg("b",t,e,n))];case"NotEqual":return[pu(Wg("a",t,e,n),Wg("b",t,e,n))];case"Greater":return[ru(Wg("a",t,e,n),Wg("b",t,e,n))];case"GreaterEqual":return[iu(Wg("a",t,e,n),Wg("b",t,e,n))];case"Less":return[su(Wg("a",t,e,n),Wg("b",t,e,n))];case"LessEqual":return[uu(Wg("a",t,e,n),Wg("b",t,e,n))];case"LogicalAnd":return[Mu(Wg("a",t,e,n),Wg("b",t,e,n))];case"LogicalNot":return[Lu(Wg("a",t,e,n))];case"LogicalOr":return[Fu(Wg("a",t,e,n),Wg("b",t,e,n))];case"Select":return[Pu(Wg("condition",t,e,n),Wg("a",t,e,n),Wg("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},xy=function(t,e,n){switch(t.op){case"BatchMatMul":case"MatMul":return[Es(Wg("a",t,e,n),Wg("b",t,e,n),Wg("transposeA",t,e,n),Wg("transposeB",t,e,n))];case"Transpose":return[Gu(Wg("x",t,e,n),Wg("perm",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Ny=function(t,e,n){switch(t.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[ns(Wg("x",t,e,n),Wg("mean",t,e,n),Wg("variance",t,e,n),Wg("offset",t,e,n),Wg("scale",t,e,n),Wg("epsilon",t,e,n))];case"LRN":return[Hu(Wg("x",t,e,n),Wg("radius",t,e,n),Wg("bias",t,e,n),Wg("alpha",t,e,n),Wg("beta",t,e,n))];case"Softmax":return[Ee(Wg("x",t,e,n))];case"LogSoftmax":return[Ie(Wg("x",t,e,n))];case"SparseToDense":return[ll(Wg("sparseIndices",t,e,n),Wg("outputShape",t,e,n),Wg("sparseValues",t,e,n),Wg("defaultValue",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Sy=function(t,e,n){switch(t.op){case"Max":var r=Wg("axis",t,e,n),i=Wg("keepDims",t,e,n);return[Xs(Wg("x",t,e,n),r,i)];case"Mean":return r=Wg("axis",t,e,n),i=Wg("keepDims",t,e,n),[Ys(Wg("x",t,e,n),r,i)];case"Min":return r=Wg("axis",t,e,n),i=Wg("keepDims",t,e,n),[Js(Wg("x",t,e,n),r,i)];case"Sum":return r=Wg("axis",t,e,n),i=Wg("keepDims",t,e,n),[Qs(Wg("x",t,e,n),r,i)];case"All":return r=Wg("axis",t,e,n),i=Wg("keepDims",t,e,n),[qs(Wg("x",t,e,n),r,i)];case"Any":return r=Wg("axis",t,e,n),i=Wg("keepDims",t,e,n),[Gs(Wg("x",t,e,n),r,i)];case"ArgMax":return r=Wg("axis",t,e,n),[Hs(Wg("x",t,e,n),r)];case"ArgMin":return r=Wg("axis",t,e,n),[Ks(Wg("x",t,e,n),r)];case"Prod":return r=Wg("axis",t,e,n),i=Wg("keepDims",t,e,n),[tu(Wg("x",t,e,n),r,i)];default:throw TypeError("Node type "+t.op+" is not implemented")}},Cy=function(t,e,n){switch(t.op){case"ConcatV2":case"Concat":var r=Wg("axis",t,e,n),i=Wg("tensors",t,e,n);return[No(i,r)];case"GatherV2":case"Gather":r=Wg("axis",t,e,n);var o=Wg("x",t,e,n),a=Wg("indices",t,e,n);return[Yu(o,a.asType("int32"),r)];case"ReverseV2":case"Reverse":return r=Wg("axis",t,e,n),o=Wg("x",t,e,n),[As(o,r)];case"Slice":var s=Wg("begin",t,e,n),u=Wg("size",t,e,n);return[Ps(Wg("x",t,e,n),s,u)];case"StridedSlice":s=Wg("begin",t,e,n);var l=Wg("end",t,e,n),c=Wg("strides",t,e,n),p=Wg("beginMask",t,e,n),h=Wg("endMask",t,e,n),f=Wg("ellipsisMask",t,e,n),d=Wg("newAxisMask",t,e,n),m=Wg("shrinkAxisMask",t,e,n),g=Wg("x",t,e,n);if(1===s.length&&g.shape.length>1)for(var y=1;y<g.shape.length;y++)s.push(0),l.push(g.shape[y]),c.push(c[0]);return[el(g,s,l,c,p,h,f,d,m)];case"Pack":return Gt(function(){var r=Wg("axis",t,e,n),i=Wg("tensors",t,e,n),o=i[0].shape,a=i[0].squeeze().shape,s=i.map(function(t){var e=X.arraysEqual(t.shape,o);if(!e&&!X.arraysEqual(t.squeeze().shape,a))throw new Error("the input tensors shape does not match");return e?t:t.reshape(o)});return[aa(s,r)]});case"Unpack":return Gt(function(){var r=Wg("axis",t,e,n),i=Wg("tensor",t,e,n);return la(i,r)});case"Tile":var v=Wg("reps",t,e,n);return[sa(Wg("x",t,e,n),v)];case"Split":case"SplitV":r=Wg("axis",t,e,n);var b=Wg("numOrSizeSplits",t,e,n);return ko(Wg("x",t,e,n),b,r);case"ScatterNd":a=Wg("indices",t,e,n);var w=Wg("values",t,e,n),x=Wg("shape",t,e,n);return[rl(a,w,x)];case"GatherNd":var N=Wg("x",t,e,n);return a=Wg("indices",t,e,n),[cl(N,a)];case"SparseToDense":a=Wg("sparseIndices",t,e,n),x=Wg("outputShape",t,e,n);var S=Wg("sparseValues",t,e,n),C=Wg("defaultValue",t,e,n);return[ll(a,S,x,S.dtype===C.dtype?C:C.asType(S.dtype))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Ey=function(t,e,n){switch(t.op){case"FFT":return[il(Wg("x",t,e,n))];case"IFFT":return[ol(Wg("x",t,e,n))];case"RFFT":return[al(Wg("x",t,e,n))];case"IRFFT":return[sl(Wg("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Iy=function(t,e,n){switch(t.op){case"Cast":return[Wo(Wg("x",t,e,n),Wg("dtype",t,e,n))];case"ExpandDims":var r=Wg("axis",t,e,n);return[Go(Wg("x",t,e,n),r)];case"Squeeze":return r=Wg("axis",t,e,n),[oa(Wg("x",t,e,n),r)];case"Reshape":return[ra(Wg("x",t,e,n),Wg("shape",t,e,n))];case"PadV2":case"Pad":return[Xo(Wg("x",t,e,n),Hg(Wg("padding",t,e,n),2),Wg("constantValue",t,e,n))];case"SpaceToBatchND":var i=Wg("blockShape",t,e,n),o=Hg(Wg("paddings",t,e,n),2);return[ia(Wg("x",t,e,n),i,o)];case"BatchToSpaceND":i=Wg("blockShape",t,e,n);var a=Hg(Wg("crops",t,e,n),2);return[Uo(Wg("x",t,e,n),i,a)];case"DepthToSpace":var s=Wg("blockSize",t,e,n),u=Wg("dataFormat",t,e,n).toUpperCase();return[qo(Wg("x",t,e,n),s,u)];default:throw TypeError("Node type "+t.op+" is not implemented")}};function ky(t,e,n){var r=function(t,e,n){switch(t.category){case"arithmetic":return hy(t,e,n);case"basic_math":return fy(t,e,n);case"control":return function(t,e,n){return Bg(this,void 0,void 0,function(){var r,i,o,a,s,u,l,c,p,h,f,d,m,g,y,v,b,w,x,N,S,C,E,I,k,A,T,R,D,O,_,M,L,F;return Ug(this,function(z){switch(z.label){case 0:switch(t.op){case"LoopCond":return[3,1];case"Switch":return[3,2];case"Merge":return[3,4];case"Enter":return[3,5];case"Exit":return[3,6];case"NextIteration":return[3,7];case"TensorArrayV3":return[3,8];case"TensorArrayWriteV3":return[3,9];case"TensorArrayReadV3":return[3,10];case"TensorArrayGatherV3":return[3,11];case"TensorArrayScatterV3":return[3,12];case"TensorArrayConcatV3":return[3,13];case"TensorArraySplitV3":return[3,14];case"TensorArraySizeV3":return[3,15];case"TensorArrayCloseV3":return[3,16]}return[3,17];case 1:return[2,[Wg("pred",t,e,n).clone()]];case 2:return r=Wg("pred",t,e,n),i=Wg("data",t,e,n),[4,r.data()];case 3:return[2,z.sent()[0]?[void 0,i.clone()]:[i.clone(),void 0]];case 4:return[2,(o=t.inputNames.find(function(t){return void 0!==Vg(t,e,n)}))?[Vg(o,e,n).clone()]:void 0];case 5:return a=Wg("frameName",t,e,n),s=Wg("tensor",t,e,n),n.enterFrame(a),[2,[s.clone()]];case 6:return u=Wg("tensor",t,e,n),n.exitFrame(),[2,[u.clone()]];case 7:return l=Wg("tensor",t,e,n),n.nextIteration(),[2,[l.clone()]];case 8:return c=Wg("size",t,e,n),p=Wg("dtype",t,e,n),h=Wg("elementShape",t,e,n),f=Wg("dynamicSize",t,e,n),d=Wg("clearAfterRead",t,e,n),m=Wg("identicalElementShapes",t,e,n),g=Wg("name",t,e,n),y=new dy(g,p,c,h,m,f,d),n.addTensorArray(y),[2,[De(y.id),De(1)]];case 9:return v=Wg("tensorArrayId",t,e,n),b=Wg("index",t,e,n),w=Wg("tensor",t,e,n),n.getTensorArray(v).write(b,w),[2,[De(1)]];case 10:return x=Wg("tensorArrayId",t,e,n),N=Wg("index",t,e,n),[2,[n.getTensorArray(x).read(N)]];case 11:return S=Wg("tensorArrayId",t,e,n),C=Wg("indices",t,e,n),E=Wg("dtype",t,e,n),[2,[n.getTensorArray(S).gather(C,E)]];case 12:return I=Wg("tensorArrayId",t,e,n),k=Wg("indices",t,e,n),A=Wg("tensor",t,e,n),n.getTensorArray(I).scatter(k,A),[2,[De(1)]];case 13:return T=Wg("tensorArrayId",t,e,n),R=n.getTensorArray(T),D=Wg("dtype",t,e,n),[2,[R.concat(D)]];case 14:return O=Wg("tensorArrayId",t,e,n),_=Wg("tensor",t,e,n),M=Wg("lengths",t,e,n),n.getTensorArray(O).split(M,_),[2,[De(1)]];case 15:return L=Wg("tensorArrayId",t,e,n),[2,[De(n.getTensorArray(L).size(),"int32")]];case 16:return F=Wg("tensorArrayId",t,e,n),n.getTensorArray(F).clearAndClose(),[2,[]];case 17:throw TypeError("Node type "+t.op+" is not implemented")}})})}(t,e,n);case"convolution":return my(t,e,n);case"creation":return gy(t,e,n);case"dynamic":return function(t,e,n){return Bg(this,void 0,void 0,function(){var r,i,o,a,s;return Ug(this,function(u){switch(u.label){case 0:switch(t.op){case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":return[3,1];case"Where":return[3,3];case"ListDiff":return[3,5]}return[3,7];case 1:return r=Wg("boxes",t,e,n),i=Wg("scores",t,e,n),o=Wg("maxOutputSize",t,e,n),a=Wg("iouThreshold",t,e,n),s=Wg("scoreThreshold",t,e,n),[4,Dl.nonMaxSuppressionAsync(r,i,o,a,s)];case 2:return[2,[u.sent()]];case 3:return[4,Bu(Wg("condition",t,e,n))];case 4:return[2,[u.sent()]];case 5:return[4,ca(Wg("x",t,e,n),Wg("y",t,e,n))];case 6:return[2,u.sent()];case 7:throw TypeError("Node type "+t.op+" is not implemented")}})})}(t,e,n);case"evaluation":return yy(t,e,n);case"image":return by(t,e,n);case"graph":return vy(t,e,n);case"logical":return wy(t,e,n);case"matrices":return xy(t,e,n);case"normalization":return Ny(t,e,n);case"reduction":return Sy(t,e,n);case"slice_join":return Cy(t,e,n);case"spectral":return Ey(t,e,n);case"transformation":return Iy(t,e,n);default:throw TypeError("Node type "+t.op+" is not implemented")}}(t,e,n);return r instanceof Promise?r.then(function(t){return[].concat(t)}):[].concat(r)}var Ay=function(){function t(t,e){this.weightMap=t,this.tensorArrayMap=e,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return t.prototype.newFrame=function(t,e){return{id:t,frameName:e,iterationId:0}},Object.defineProperty(t.prototype,"currentContext",{get:function(){return this.contexts},set:function(t){this.contexts!==t&&(this.contexts=t,this.generateCurrentContextIds())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextId",{get:function(){return this._currentContextIds[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextIds",{get:function(){return this._currentContextIds},enumerable:!0,configurable:!0}),t.prototype.generateCurrentContextIds=function(){for(var t=[],e=0;e<this.contexts.length-1;e++){var n=this.contexts.slice(0,this.contexts.length-e);t.push(this.contextIdforContexts(n))}t.push(""),this._currentContextIds=t},t.prototype.contextIdforContexts=function(t){return t?t.map(function(t){return 0===t.id&&0===t.iterationId?"":t.frameName+"-"+t.iterationId}).join("/"):""},t.prototype.enterFrame=function(t){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,t)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))},t.prototype.exitFrame=function(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},t.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},t.prototype.getWeight=function(t){return this.weightMap[t]},t.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},t.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},t}(),Ty=function(){function t(t){this.graph=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=t.placeholders,this._outputs=t.outputs,this.compile()}return Object.defineProperty(t.prototype,"weightMap",{get:function(){return this._weightMap},set:function(t){var e=Object.keys(t).map(function(e){return t[e].map(function(t){return t.id})});this.weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.placeholders.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this._outputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(t){return t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.outputs.map(function(t){return t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isControlFlowModel",{get:function(){return this.graph.withControlFlow},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"isDynamicShapeModel",{get:function(){return this.graph.withDynamicShape},enumerable:!0,configurable:!0}),t.prototype.compile=function(t){if(!this.graph.withControlFlow&&!this.graph.withDynamicShape){var e=[],n=t||this.graph.placeholders,r=n.map(function(t){return t.name}).sort().join(this.SEPERATOR);if(!this.compiledMap.get(r)){for(var i=n.concat(this.graph.weights),o={};i.length>0;){var a=i.pop();o[a.name]=!0,e.push(a),a.children.forEach(function(t){!o[t.name]&&t.inputNames.every(function(t){var e=jg(t)[0];return o[e]})&&i.push(t)})}this.compiledMap.set(r,e)}}},t.prototype.execute=function(t,e,n){var r=this;void 0===e&&(e=!0);var i=Object.keys(t).sort();this.checkInput(t,e),this.checkInputShapeAndType(t,e),this.compile(i.map(function(t){return r.graph.nodes[t]}));var o=this.calculateOutputs(n);this.checkOutput(this.compiledMap.get(i.join(this.SEPERATOR)),o);var a={};return Gt(function(){for(var e=new Ay(r._weightMap,a),n=Pg({},r.weightMap,t),s=r.getFrozenTensorIds(n),u={},l=r.compiledMap.get(i.join(r.SEPERATOR)),c=0;c<l.length;c++){var p=l[c];if(n[p.name]||(n[p.name]=ky(p,n,e),r.checkTensorForDisposal(p.name,p,n,e,s,o,u)),o.every(function(t){return!!n[t]}))break}return r.findOutputs(n,e,o)})},t.prototype.getFrozenTensorIds=function(t){var e=[].concat.apply([],Object.keys(t).map(function(e){return t[e]}).map(function(t){return t.map(function(t){return t.id})}));return new Set(e)},t.prototype.checkTensorForDisposal=function(t,e,n,r,i,o,a){"control"!==e.category&&-1===o.indexOf(t)&&(n[t].forEach(function(t){null!=t&&(a[t.id]=(a[t.id]||0)+e.children.length)}),e.inputs.forEach(function(t){if("control"!==t.category){var e=function(t,e,n){return e[qg(t,n.currentContextId)]}(t.name,n,r);null!=e&&e.forEach(function(t){if(t&&!i.has(t.id)){var e=a[t.id];1===e?(t.dispose(),delete a[t.id]):null!=e&&a[t.id]--}})}}))},t.prototype.executeAsync=function(t,e){return Bg(this,void 0,void 0,function(){var n,r,i,o,a,s,u,l,c=this;return Ug(this,function(p){switch(p.label){case 0:return this.checkInput(t,!1),this.checkInputShapeAndType(t,!1),n={},r=new Ay(this._weightMap,n),i=this.calculateOutputs(e),[4,this.executeWithControlFlow(t,r,i)];case 1:return o=p.sent(),a=this.findOutputs(o,r,e),s=Object.keys(a).map(function(t){return a[t].id}),u=Object.keys(t).map(function(e){return t[e].map(function(t){return t.id})}),l=[].concat.apply([],u),Object.keys(o).forEach(function(t){o[t].forEach(function(t){t&&!t.isDisposed&&-1===s.indexOf(t.id)&&-1===l.indexOf(t.id)&&-1===c.weightIds.indexOf(t.id)&&t.dispose()})}),[2,a]}})})},t.prototype.executeWithControlFlow=function(t,e,n){return Bg(this,void 0,void 0,function(){var r,i,o,a,s,u,l,c,p=this;return Ug(this,function(h){switch(h.label){case 0:r=Object.keys(t),i=r.map(function(t){return p.graph.nodes[t]}),o=i.concat(this.graph.weights).map(function(t){return{node:t,contexts:e.currentContext}}),a=Pg({},this.weightMap,t),s={},u=this.getFrozenTensorIds(a),l={},h.label=1;case 1:return o.length>0?(c=this.processStack(i,o,e,a,l,u,n,s),[4,Promise.all(c)]):[3,3];case 2:return h.sent(),[3,1];case 3:return[2,a]}})})},t.prototype.processStack=function(t,e,n,r,i,o,a,s){for(var u=this,l=[],c=function(){var c=e.pop();n.currentContext=c.contexts;var h="";if("Enter"===c.node.op&&Wg("isConstant",c.node,r,n)&&(h=jg(c.node.name,n)[0]),-1===t.indexOf(c.node)){var f=ky(c.node,r,n);h||(h=jg(c.node.name,n)[0]);var d=n.currentContext;f instanceof Promise?l.push(f.then(function(t){return r[h]=t,n.currentContext=d,u.checkTensorForDisposal(h,c.node,r,n,o,a,s),u.processChildNodes(c.node,e,n,r,i),t})):(r[h]=f,p.checkTensorForDisposal(h,c.node,r,n,o,a,s),p.processChildNodes(c.node,e,n,r,i))}else p.processChildNodes(c.node,e,n,r,i)},p=this;e.length>0;)c();return l},t.prototype.processChildNodes=function(t,e,n,r,i){t.children.forEach(function(t){var o=jg(t.name,n)[0];i[o]||("Merge"===t.op?t.inputNames.some(function(t){return!!Vg(t,r,n)})&&(i[o]=!0,e.push({contexts:n.currentContext,node:t})):t.inputNames.every(function(t){return!!Vg(t,r,n)})&&(i[o]=!0,e.push({contexts:n.currentContext,node:t})))})},t.prototype.calculateOutputs=function(t){return!t||t instanceof Array||(t=[t]),t||this.graph.outputs.map(function(t){return t.name})},t.prototype.findOutputs=function(t,e,n){return this.calculateOutputs(n).reduce(function(n,r){return n[r]=Vg(r,t,e),n},{})},t.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach(function(e){return t.weightMap[e].forEach(function(t){return t.dispose()})})},t.prototype.checkInputShapeAndType=function(t,e){void 0===e&&(e=!0),this.placeholders.forEach(function(n){var r=t[n.name];if(e||r){var i=r[0];if(n.attrParams.shape&&n.attrParams.shape.value){var o=n.attrParams.shape.value,a=o.length===i.shape.length&&i.shape.every(function(t,e){return-1===o[e]||o[e]===t});X.assert(a,function(){return"The shape of dict['"+n.name+"'] provided in model.execute(dict) must be ["+o+"], but was ["+i.shape+"]"})}n.attrParams.dtype&&n.attrParams.dtype.value&&X.assert(i.dtype===n.attrParams.dtype.value,function(){return"The dtype of dict['"+n.name+"'] provided in model.execute(dict) must be "+n.attrParams.dtype.value+", but was "+i.dtype})}})},t.prototype.checkInput=function(t,e){var n=this;void 0===e&&(e=!0);var r=Object.keys(t),i=[],o=[];this.inputNodes.forEach(function(t){-1===r.indexOf(t)&&i.push(t)}),r.forEach(function(t){-1===n.inputNodes.indexOf(t)&&o.push(t)});var a=o.filter(function(t){return!n.graph.nodes[t]});if(i.length>0&&e)throw new Error("The dict provided in model.execute(dict) has the keys ["+r+"], but is missing the required keys: ["+i+"].");if(o.length>0&&e)throw new Error("The dict provided in model.execute(dict) has unused keys: ["+o+"]. Please provide only the following keys: ["+this.inputNodes+"].");if(a.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+a+"] not part of model graph.")},t.prototype.checkOutput=function(t,e){var n=t.map(function(t){return t.name}),r=[];if(e.forEach(function(t){var e=Gg(t)[0];-1===n.indexOf(e)&&r.push(e)}),r.length>0)throw new Error("The following outputs are not generated by the execution: ["+r+"].")},t}(),Ry="?tfjs-format=file",Dy="model.json",Oy=function(){function t(t,e){void 0===e&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",null==e&&(this.loadOptions={})}return Object.defineProperty(t.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),t.prototype.findIOHandler=function(){var t=this.modelUrl;if(null!=t.load)this.handler=t;else if(null!=this.loadOptions.requestInit)this.handler=Tc.browserHTTPRequest(t,this.loadOptions);else{var e=Tc.getLoadHandlers(t,this.loadOptions.onProgress);if(0===e.length)e.push(Tc.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for URL '"+[t]+"'");this.handler=e[0]}},t.prototype.load=function(){return Bg(this,void 0,void 0,function(){var t,e,n;return Ug(this,function(r){switch(r.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return t=r.sent(),e=t.modelTopology,this.version=e.versions.producer+"."+e.versions.minConsumer,n=Tc.decodeWeights(t.weightData,t.weightSpecs),this.executor=new Ty(py.Instance.transformGraph(e)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),[2,!0]}})})},t.prototype.predict=function(t,e){return this.execute_(t,!0,this.outputNodes)},t.prototype.constructTensorMap=function(t){var e=t instanceof lt?[t]:t;if(e.length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+e.length+" input tensors.");return this.inputNodes.reduce(function(t,n,r){return t[n]=e[r],t},{})},t.prototype.execute=function(t,e){return this.execute_(t,!1,e)},t.prototype.execute_=function(t,e,n){if(void 0===e&&(e=!0),n=n||this.outputNodes,(t instanceof lt||Array.isArray(t))&&(t=this.constructTensorMap(t)),this.executor.isControlFlowModel||this.executor.isDynamicShapeModel)throw new Error("The model contains control flow or dynamic shape ops, please use executeAsync method");var r=this.executor.execute(this.convertTensorMapToTensorsMap(t),e,n),i=Object.keys(r);return Array.isArray(n)&&n.length>1?n.map(function(t){return r[t]}):r[i[0]]},t.prototype.executeAsync=function(t,e){return Bg(this,void 0,void 0,function(){var n,r;return Ug(this,function(i){switch(i.label){case 0:if(!this.executor.isControlFlowModel&&!this.executor.isDynamicShapeModel)throw new Error("The model does not contain control flow or dynamic shape ops, please use execute method for better performance.");return e=e||this.outputNodes,(t instanceof lt||Array.isArray(t))&&(t=this.constructTensorMap(t)),[4,this.executor.executeAsync(this.convertTensorMapToTensorsMap(t),e)];case 1:return n=i.sent(),r=Object.keys(n),[2,Array.isArray(e)&&e.length>1?e.map(function(t){return n[t]}):n[r[0]]]}})})},t.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce(function(e,n){return e[n]=[t[n]],e},{})},t.prototype.dispose=function(){this.executor.dispose()},t}();var _y=function(t,e){return(_y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function My(t,e){function n(){this.constructor=t}_y(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function Ly(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})}function Fy(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=e.call(t,a)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}var zy="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Py(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function By(t,e){return t(e={exports:{}},e.exports),e.exports}var Uy=By(function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),Wy=By(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),Vy=By(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),jy=By(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),qy=By(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,o=e.i;return e.w=r=r+1640531527|0,n=i[o+34&127],t=i[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[o]=n^t,e.i=o,n+(r^r>>>16)|0},function(t,e){var n,r,i,o,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,o=-32;o<u;++o)e&&(r^=e.charCodeAt((o+32)%e.length)),0===o&&(a=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,i=0==(n=s[127&o]^=r+a)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=a,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),Gy=By(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),Hy=By(function(t){!function(e,n){var r,i=(0,eval)("this"),o=256,a=6,s="random",u=n.pow(o,a),l=n.pow(2,52),c=2*l,p=o-1;function h(t,h,g){var y=[],v=d(function t(e,n){var r,i=[],o=typeof e;if(n&&"object"==o)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=i.navigator,a=n&&n.plugins;return[+new Date,i,a,i.screen,m(e)]}}():t,3),y),b=new function(t){var e,n=t.length,r=this,i=0,a=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i<o;)s[i]=i++;for(i=0;i<o;i++)s[i]=s[a=p&a+t[i%n]+(e=s[i])],s[a]=e;(r.g=function(t){for(var e,n=0,i=r.i,a=r.j,s=r.S;t--;)e=s[i=p&i+1],n=n*o+s[p&(s[i]=s[a=p&a+e])+(s[a]=e)];return r.i=i,r.j=a,n})(o)}(y),w=function(){for(var t=b.g(a),e=u,n=0;t<l;)t=(t+n)*o,e*=o,n=b.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return w.int32=function(){return 0|b.g(4)},w.quick=function(){return b.g(4)/4294967296},w.double=w,d(m(b.S),e),(h.pass||g||function(t,e,r,i){return i&&(i.S&&f(i,b),t.state=function(){return f(b,{})}),r?(n[s]=t,e):t})(w,v,"global"in h?h.global:this==n,h.state)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function d(t,e){for(var n,r=t+"",i=0;i<r.length;)e[p&i]=p&(n^=19*e[p&i])+r.charCodeAt(i++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=h,d(n.random(),e),t.exports){t.exports=h;try{r=require("crypto")}catch(t){}}}([],Math)});Hy.alea=Uy,Hy.xor128=Wy,Hy.xorwow=Vy,Hy.xorshift7=jy,Hy.xor4096=qy,Hy.tychei=Gy;var Ky=Hy.alea,$y=By(function(t,e){function n(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function r(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function i(t,e){if(void 0===e&&(e=[]),null==e&&(e=[]),Array.isArray(t)||l(t))for(var n=0;n<t.length;++n)i(t[n],e);else e.push(t);return e}function o(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function a(t){return t%1==0}function s(t,e){var n=e.length;return r((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&t<n}),function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t}),r(t.every(function(t){return a(t)}),function(){return"All values in axis param must be integers but got axis "+t}),t.map(function(t){return t<0?n+t:t})}function u(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function l(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function c(t){return"string"==typeof t||t instanceof String}function p(t){return"boolean"==typeof t}function h(t){return"number"==typeof t}function f(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}Object.defineProperty(e,"__esModule",{value:!0}),e.shuffle=n,e.clamp=function(t,e,n){return Math.max(t,Math.min(e,n))},e.nearestLargerEven=function(t){return t%2==0?t:t+1},e.sum=function(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e},e.randUniform=function(t,e){var n=Math.random();return e*n+(1-n)*t},e.distSquared=function(t,e){for(var n=0,r=0;r<t.length;r++){var i=Number(t[r])-Number(e[r]);n+=i*i}return n},e.assert=r,e.assertShapesMatch=function(t,e,n){void 0===n&&(n=""),r(o(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})},e.assertNonNull=function(t){r(null!=t,function(){return"The input to the tensor constructor must be a non-null value."})},e.flatten=i,e.sizeFromShape=function(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e},e.isScalarShape=function(t){return 0===t.length},e.arraysEqual=o,e.isInt=a,e.tanh=function(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)},e.sizeToSquarishShape=function(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]},e.createShuffledIndices=function(t){for(var e=new Uint32Array(t),r=0;r<t;++r)e[r]=r;return n(e),e},e.rightPad=function(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)},e.repeatedTry=function(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise(function(r,i){var o=0,a=function(){if(t())r();else{var s=e(++o);null!=n&&o>=n?i():setTimeout(a,s)}};a()})},e.inferFromImplicitShape=function(t,e){for(var n=1,r=-1,i=0;i<t.length;++i)if(t[i]>=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var o=t.slice();return o[r]=e/n,o},e.parseAxisParam=s,e.squeezeShape=function(t,e){for(var n=[],r=[],i=null==e?null:s(e,t).sort(),o=0,a=0;a<t.length;++a){if(null!=i){if(i[o]===a&&1!==t[a])throw new Error("Can't squeeze axis "+a+" since its dim '"+t[a]+"' is not 1");(null==i[o]||i[o]>a)&&1===t[a]&&(n.push(t[a]),r.push(a)),i[o]<=a&&o++}1!==t[a]&&(n.push(t[a]),r.push(a))}return{newShape:n,keptDims:r}},e.getTypedArrayFromDType=function(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n},e.getArrayFromDType=function(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n},e.checkComputationForErrors=function(t,e,n){if("float32"===e)for(var r=0;r<t.length;r++){var i=t[r];if(isNaN(i)||!isFinite(i))throw Error("The result of the '"+n+"' is "+i+".")}},e.checkConversionForErrors=u,e.hasEncodingLoss=function(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)},e.isTypedArray=l,e.bytesPerElement=function(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)},e.bytesFromStringArray=function(t){if(null==t)return 0;var e=0;return t.forEach(function(t){return e+=2*t.length}),e},e.isString=c,e.isBoolean=p,e.isNumber=h,e.inferDtype=function t(e){return Array.isArray(e)?t(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":h(e)?"float32":c(e)?"string":p(e)?"bool":"float32"},e.isFunction=function(t){return!!(t&&t.constructor&&t.call&&t.apply)},e.nearestDivisor=function(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t},e.computeStrides=function(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n},e.toTypedArray=function(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=i(t)),n&&u(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r}throw new Error("Unknown data type "+e)},e.toNestedArray=function(t,e){if(0===t.length)return e[0];var n=t.reduce(function(t,e){return t*e});if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var i=new Array;if(1===n.length)for(var o=n[0],a=0;a<o;a++)i[a]=r[e+a];else{o=n[0];var s=n.slice(1),u=s.reduce(function(t,e){return t*e});for(a=0;a<o;a++)i[a]=t(e+a*u,s,r)}return i}(0,t,e)},e.makeOnesTypedArray=function(t,e){for(var n=f(t,e),r=0;r<n.length;r++)n[r]=1;return n},e.makeZerosTypedArray=f,e.now=function(){if("undefined"!=typeof performance)return performance.now();if("undefined"!=typeof process){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}throw new Error("Cannot measure time in this environment. You should run tf.js in the browser or in Node.js")},e.assertNonNegativeIntegerDimensions=function(t){t.forEach(function(e){r(Number.isInteger(e)&&e>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}});Py($y);$y.shuffle,$y.clamp,$y.nearestLargerEven,$y.sum,$y.randUniform,$y.distSquared,$y.assert,$y.assertShapesMatch,$y.assertNonNull,$y.flatten,$y.sizeFromShape,$y.isScalarShape,$y.arraysEqual,$y.isInt,$y.tanh,$y.sizeToSquarishShape,$y.createShuffledIndices,$y.rightPad,$y.repeatedTry,$y.inferFromImplicitShape,$y.parseAxisParam,$y.squeezeShape,$y.getTypedArrayFromDType,$y.getArrayFromDType,$y.checkComputationForErrors,$y.checkConversionForErrors,$y.hasEncodingLoss;var Xy=$y.isTypedArray,Yy=($y.bytesPerElement,$y.bytesFromStringArray,$y.isString,$y.isBoolean,$y.isNumber,$y.inferDtype,$y.isFunction,$y.nearestDivisor,$y.computeStrides,$y.toTypedArray,$y.toNestedArray,$y.makeOnesTypedArray,$y.makeZerosTypedArray,$y.now,$y.assertNonNegativeIntegerDimensions,By(function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var n=7;function r(t,e,r){var o;return o=Array.isArray(t)?parseFloat(t[0].toFixed(n))+" + "+parseFloat(t[1].toFixed(n))+"j":$y.isString(t)?"'"+t+"'":"bool"===r?i(t):parseFloat(t.toFixed(n)).toString(),$y.rightPad(o,e)}function i(t){return 0===t?"false":"true"}function o(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}e.tensorToString=function(t,e,n,a){var s=$y.computeStrides(e),u=function(t,e,n,i){var a=$y.sizeFromShape(e),s=i[i.length-1],u=new Array(s).fill(0),l=e.length,c="complex64"===n?o(t):t;if(l>1)for(var p=0;p<a/s;p++)for(var h=p*s,f=0;f<s;f++)u[f]=Math.max(u[f],r(c[h+f],0,n).length);return u}(t,e,n,s),l=e.length,c=function t(e,n,a,s,u,l){void 0===l&&(l=!0);var c="complex64"===a?2:1,p=n[0],h=n.length;if(0===h)return"complex64"===a?[r(o(e)[0],0,a)]:"bool"===a?[i(e[0])]:[e[0].toString()];if(1===h){if(p>20){var f=3*c,d=Array.from(e.slice(0,f)),m=Array.from(e.slice(p-3*c,p));return"complex64"===a&&(d=o(d),m=o(m)),["["+d.map(function(t,e){return r(t,u[e],a)}).join(", ")+", ..., "+m.map(function(t,e){return r(t,u[p-3+e],a)}).join(", ")+"]"]}return["["+("complex64"===a?o(e):Array.from(e)).map(function(t,e){return r(t,u[e],a)}).join(", ")+"]"]}var g=n.slice(1),y=s.slice(1),v=s[0]*c,b=[];if(p>20){for(var w=0;w<3;w++){var x=(N=w*v)+v;b.push.apply(b,t(e.slice(N,x),g,a,y,u,!1))}b.push("...");for(w=p-3;w<p;w++){x=(N=w*v)+v;b.push.apply(b,t(e.slice(N,x),g,a,y,u,w===p-1))}}else for(w=0;w<p;w++){var N;x=(N=w*v)+v;b.push.apply(b,t(e.slice(N,x),g,a,y,u,w===p-1))}var S=2===h?",":"";b[0]="["+b[0]+S;for(w=1;w<b.length-1;w++)b[w]=" "+b[w]+S;var C=",\n";for(w=2;w<h;w++)C+="\n";return b[b.length-1]=" "+b[b.length-1]+"]"+(l?"":C),b}(t,e,n,s,u),p=["Tensor"];return a&&(p.push("  dtype: "+n),p.push("  rank: "+l),p.push("  shape: ["+e+"]"),p.push("  values:")),p.push(c.map(function(t){return"    "+t}).join("\n")),p.join("\n")}}));Py(Yy);Yy.tensorToString;var Jy=By(function(t,e){var n,r=zy&&zy.__extends||(n=function(t,e){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)},function(t,e){function r(){this.constructor=t}n(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}),i=zy&&zy.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(t){o(t)}}function s(t){try{u(r.throw(t))}catch(t){o(t)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})},o=zy&&zy.__generator||function(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=e.call(t,a)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}};Object.defineProperty(e,"__esModule",{value:!0});var a=$y,s=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=$y.sizeFromShape(t),null!=n){var i=n.length;$y.assert(i===this.size,function(){return"Length of values '"+i+"' does not match the size inferred by the shape '"+r.size+"'."})}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||$y.getArrayFromDType(e,this.size),this.strides=a.computeStrides(t)}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),$y.assert(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"});var i=this.locToIndex(n);this.values[i]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=t[t.length-1],r=0;r<t.length-1;++r)n+=this.strides[r]*t[r];return this.values[n]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return p.make(this.shape,{values:this.values},this.dtype)},t}();e.TensorBuffer=s;var u=null,l=null,c=null;e.setTensorTracker=function(t){u=t},e.setOpHandler=function(t){l=t},e.setDeprecationWarningFn=function(t){c=t};var p=function(){function t(t,e,n,r,i){this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=$y.sizeFromShape(t),this.strides=a.computeStrides(t),this.dataId=null!=r?r:{},this.id=u().nextTensorId(),this.rankType=this.rank<5?this.rank.toString():"higher",u().registerTensor(this,i),null!=n&&u().write(this.dataId,n)}return t.make=function(e,n,r,i){return new t(e,r,n.values,n.dataId,i)},t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),$y.assert(1===this.size,function(){return"The array must have only 1 element."}),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,i){return this.throwIfDisposed(),this.reshape([t,e,n,r,i])},t.prototype.asType=function(t){return this.throwIfDisposed(),l.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return i(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,l.buffer(this.shape,this.dtype,t)]}})})},t.prototype.bufferSync=function(){return l.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return i(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,a.toNestedArray(this.shape,t)]}})})},t.prototype.arraySync=function(){return a.toNestedArray(this.shape,this.dataSync())},t.prototype.data=function(){return i(this,void 0,void 0,function(){return o(this,function(t){return this.throwIfDisposed(),[2,u().read(this.dataId)]})})},t.prototype.dataSync=function(){return this.throwIfDisposed(),u().readSync(this.dataId)},t.prototype.dispose=function(){this.isDisposed||(u().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},t.prototype.toFloat=function(){return this.asType("float32")},t.prototype.toInt=function(){return this.asType("int32")},t.prototype.toBool=function(){return this.asType("bool")},t.prototype.print=function(t){return void 0===t&&(t=!1),l.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),l.reshape(this,t)},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},t.prototype.expandDims=function(t){return void 0===t&&(t=0),l.expandDims(this,t)},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),l.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),l.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),l.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),l.oneHot(this,t,e,n)},t.prototype.toString=function(t){void 0===t&&(t=!1);var e=this.dataSync();return Yy.tensorToString(e,this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),l.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),l.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),l.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),l.dot(this,t)},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),l.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),l.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),l.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),l.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),l.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),l.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),l.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),l.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,i){return void 0===n&&(n=.001),c("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,i,r,n)},t.prototype.batchNorm=function(t,e,n,r,i){return void 0===i&&(i=.001),this.throwIfDisposed(),l.batchNorm(this,t,e,n,r,i)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),l.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),l.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),l.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),l.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),l.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),l.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),l.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),l.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),l.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),l.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),l.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),l.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),l.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),l.div(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),l.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),l.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),l.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),l.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),l.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),l.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),l.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),l.modStrict(this,t)},t.prototype.squaredDifference=function(t){return this.throwIfDisposed(),l.squaredDifference(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),l.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),l.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),l.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),l.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),l.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),l.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),l.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),l.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),l.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),l.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),l.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),l.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),l.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),l.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),l.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),l.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),l.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),l.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),l.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),l.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),l.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),l.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),l.sign(this)},t.prototype.exp=function(){return this.throwIfDisposed(),l.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),l.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),l.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),l.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),l.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),l.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),l.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),l.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),l.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),l.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),l.relu(this)},t.prototype.elu=function(){return this.throwIfDisposed(),l.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),l.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),l.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),l.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),l.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),l.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),l.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),l.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),l.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),l.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),l.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),l.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),l.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),l.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),l.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),l.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),l.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),l.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),l.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),l.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),l.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),l.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),l.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),l.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),l.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),l.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),l.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),l.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,i,o){return void 0===r&&(r="NWC"),void 0===i&&(i=1),this.throwIfDisposed(),l.conv1d(this,t,e,n,r,i,o)},t.prototype.conv2d=function(t,e,n,r,i,o){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),l.conv2d(this,t,e,n,r,i,o)},t.prototype.conv2dTranspose=function(t,e,n,r,i){return this.throwIfDisposed(),l.conv2dTranspose(this,t,e,n,r,i)},t.prototype.depthwiseConv2D=function(t,e,n,r,i,o){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),l.depthwiseConv2d(this,t,e,n,r,i,o)},t.prototype.separableConv2d=function(t,e,n,r,i,o){return void 0===i&&(i=[1,1]),void 0===o&&(o="NHWC"),this.throwIfDisposed(),l.separableConv2d(this,t,e,n,r,i,o)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),l.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),l.maxPool(this,t,e,n,r)},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),l.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,i){return this.throwIfDisposed(),l.pool(this,t,e,n,r,i)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),h.variable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),l.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),l.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),l.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),l.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,i,o,a,s){return void 0===r&&(r=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===s&&(s=0),this.throwIfDisposed(),l.stridedSlice(this,t,e,n,r,i,o,a,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),l.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),l.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),l.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),l.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),l.spectral.irfft(this)},t}();e.Tensor=p,Object.defineProperty(p,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var h=function(t){function e(e,n,r){void 0===n&&(n=!0);var i=t.call(this,e.shape,e.dtype,null,e.dataId)||this;i.trainable=n,i.name=r,null==i.name&&(i.name=u().nextVariableId().toString());try{u().registerVariable(i)}catch(t){throw u().disposeTensor(i),t}return i}return r(e,t),e.variable=function(t,n,r,i){return void 0===n&&(n=!0),null!=i&&i!==t.dtype&&(t=t.asType(i)),new e(t,n,r)},e.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!$y.arraysEqual(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");u().disposeTensor(this),this.dataId=t.dataId,u().registerTensor(this)},e}(p);e.Variable=h,Object.defineProperty(h,Symbol.hasInstance,{value:function(t){return t instanceof p&&null!=t.assign&&t.assign instanceof Function}});var f=h.variable;e.variable=f});Py(Jy);Jy.TensorBuffer,Jy.setTensorTracker,Jy.setOpHandler,Jy.setDeprecationWarningFn,Jy.Tensor,Jy.Variable,Jy.variable;var Zy=By(function(t,e){var n,r,i,o;Object.defineProperty(e,"__esModule",{value:!0}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(e.Rank||(e.Rank={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(n||(n={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(r||(r={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(i||(i={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(o||(o={}));var a={float32:i,int32:n,bool:r,complex64:o};function s(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return a[t][e]}e.upcastType=s,e.sumOutType=function(t){return s(t,"int32")}});Py(Zy);Zy.Rank,Zy.upcastType,Zy.sumOutType;var Qy=By(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.makeTypesMatch=function(t,e){if(t.dtype===e.dtype)return[t,e];var n=Zy.upcastType(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]},e.assertTypesMatch=function(t,e){$y.assert(t.dtype===e.dtype,function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"})},e.isTensorInList=function(t,e){for(var n=0;n<e.length;n++)if(e[n].id===t.id)return!0;return!1},e.flattenNameArrayMap=function(t,e){var n=[];if(t instanceof Jy.Tensor)n.push(t);else for(var r=t,i=0;i<e.length;i++)n.push(r[e[i]]);return n},e.unflattenToNameArrayMap=function(t,e){if(t.length!==e.length)throw new Error("Cannot unflatten Tensor[], keys and arrays are not of same length.");for(var n={},r=0;r<t.length;r++)n[t[r]]=e[r];return n},e.getTensorsInContainer=function(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof Jy.Tensor)n.push(e);else if(i=e,Array.isArray(i)||"object"==typeof i){var i,o=e;for(var a in o){var s=o[a];r.has(s)||(r.add(s),t(s,n,r))}}}(t,e,new Set),e}});Py(Qy);Qy.makeTypesMatch,Qy.assertTypesMatch;var tv=Qy.isTensorInList,ev=(Qy.flattenNameArrayMap,Qy.unflattenToNameArrayMap,Qy.getTensorsInContainer),nv=function(t){return t instanceof Buffer},rv=By(function(t){"function"==typeof Object.create?t.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(t,e){t.super_=e;var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}}),iv=By(function(t){try{var e=ov;if("function"!=typeof e.inherits)throw"";t.exports=e.inherits}catch(e){t.exports=rv}}),ov=By(function(t,e){var n=Object.getOwnPropertyDescriptors||function(t){for(var e=Object.keys(t),n={},r=0;r<e.length;r++)n[e[r]]=Object.getOwnPropertyDescriptor(t,e[r]);return n},r=/%[sdj%]/g;e.format=function(t){if(!g(t)){for(var e=[],n=0;n<arguments.length;n++)e.push(a(arguments[n]));return e.join(" ")}n=1;for(var i=arguments,o=i.length,s=String(t).replace(r,function(t){if("%%"===t)return"%";if(n>=o)return t;switch(t){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(t){return"[Circular]"}default:return t}}),u=i[n];n<o;u=i[++n])d(u)||!b(u)?s+=" "+u:s+=" "+a(u);return s},e.deprecate=function(t,n){if("undefined"!=typeof process&&!0===process.noDeprecation)return t;if("undefined"==typeof process)return function(){return e.deprecate(t,n).apply(this,arguments)};var r=!1;return function(){if(!r){if(process.throwDeprecation)throw new Error(n);process.traceDeprecation?console.trace(n):console.error(n),r=!0}return t.apply(this,arguments)}};var i,o={};function a(t,n){var r={seen:[],stylize:u};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),f(n)?r.showHidden=n:n&&e._extend(r,n),y(r.showHidden)&&(r.showHidden=!1),y(r.depth)&&(r.depth=2),y(r.colors)&&(r.colors=!1),y(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=s),l(r,t,r.depth)}function s(t,e){var n=a.styles[e];return n?"["+a.colors[n][0]+"m"+t+"["+a.colors[n][1]+"m":t}function u(t,e){return t}function l(t,n,r){if(t.customInspect&&n&&N(n.inspect)&&n.inspect!==e.inspect&&(!n.constructor||n.constructor.prototype!==n)){var i=n.inspect(r,t);return g(i)||(i=l(t,i,r)),i}var o=function(t,e){if(y(e))return t.stylize("undefined","undefined");if(g(e)){var n="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(n,"string")}return m(e)?t.stylize(""+e,"number"):f(e)?t.stylize(""+e,"boolean"):d(e)?t.stylize("null","null"):void 0}(t,n);if(o)return o;var a=Object.keys(n),s=function(t){var e={};return a.forEach(function(t,n){e[t]=!0}),e}();if(t.showHidden&&(a=Object.getOwnPropertyNames(n)),x(n)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return c(n);if(0===a.length){if(N(n)){var u=n.name?": "+n.name:"";return t.stylize("[Function"+u+"]","special")}if(v(n))return t.stylize(RegExp.prototype.toString.call(n),"regexp");if(w(n))return t.stylize(Date.prototype.toString.call(n),"date");if(x(n))return c(n)}var b,S="",C=!1,E=["{","}"];return h(n)&&(C=!0,E=["[","]"]),N(n)&&(S=" [Function"+(n.name?": "+n.name:"")+"]"),v(n)&&(S=" "+RegExp.prototype.toString.call(n)),w(n)&&(S=" "+Date.prototype.toUTCString.call(n)),x(n)&&(S=" "+c(n)),0!==a.length||C&&0!=n.length?r<0?v(n)?t.stylize(RegExp.prototype.toString.call(n),"regexp"):t.stylize("[Object]","special"):(t.seen.push(n),b=C?function(t,e,n,r,i){for(var o=[],a=0,s=e.length;a<s;++a)I(e,String(a))?o.push(p(t,e,n,r,String(a),!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(p(t,e,n,r,i,!0))}),o}(t,n,r,s,a):a.map(function(e){return p(t,n,r,s,e,C)}),t.seen.pop(),function(t,e,n){return t.reduce(function(t,e){return e.indexOf("\n"),t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(""===e?"":e+"\n ")+" "+t.join(",\n  ")+" "+n[1]:n[0]+e+" "+t.join(", ")+" "+n[1]}(b,S,E)):E[0]+S+E[1]}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function p(t,e,n,r,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?s=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(s=t.stylize("[Setter]","special")),I(r,i)||(a="["+i+"]"),s||(t.seen.indexOf(u.value)<0?(s=d(n)?l(t,u.value,null):l(t,u.value,n-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(t){return"  "+t}).join("\n").substr(2):"\n"+s.split("\n").map(function(t){return"   "+t}).join("\n")):s=t.stylize("[Circular]","special")),y(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+s}function h(t){return Array.isArray(t)}function f(t){return"boolean"==typeof t}function d(t){return null===t}function m(t){return"number"==typeof t}function g(t){return"string"==typeof t}function y(t){return void 0===t}function v(t){return b(t)&&"[object RegExp]"===S(t)}function b(t){return"object"==typeof t&&null!==t}function w(t){return b(t)&&"[object Date]"===S(t)}function x(t){return b(t)&&("[object Error]"===S(t)||t instanceof Error)}function N(t){return"function"==typeof t}function S(t){return Object.prototype.toString.call(t)}function C(t){return t<10?"0"+t.toString(10):t.toString(10)}e.debuglog=function(t){if(y(i)&&(i=process.env.NODE_DEBUG||""),t=t.toUpperCase(),!o[t])if(new RegExp("\\b"+t+"\\b","i").test(i)){var n=process.pid;o[t]=function(){var r=e.format.apply(e,arguments);console.error("%s %d: %s",t,n,r)}}else o[t]=function(){};return o[t]},e.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=h,e.isBoolean=f,e.isNull=d,e.isNullOrUndefined=function(t){return null==t},e.isNumber=m,e.isString=g,e.isSymbol=function(t){return"symbol"==typeof t},e.isUndefined=y,e.isRegExp=v,e.isObject=b,e.isDate=w,e.isError=x,e.isFunction=N,e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},e.isBuffer=nv;var E=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function I(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.log=function(){var t,n;console.log("%s - %s",(n=[C((t=new Date).getHours()),C(t.getMinutes()),C(t.getSeconds())].join(":"),[t.getDate(),E[t.getMonth()],n].join(" ")),e.format.apply(e,arguments))},e.inherits=iv,e._extend=function(t,e){if(!e||!b(e))return t;for(var n=Object.keys(e),r=n.length;r--;)t[n[r]]=e[n[r]];return t};var k="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function A(t,e){if(!t){var n=new Error("Promise was rejected with a falsy value");n.reason=t,t=n}return e(t)}e.promisify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(k&&t[k]){var e;if("function"!=typeof(e=t[k]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,k,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,n,r=new Promise(function(t,r){e=t,n=r}),i=[],o=0;o<arguments.length;o++)i.push(arguments[o]);i.push(function(t,r){t?n(t):e(r)});try{t.apply(this,i)}catch(t){n(t)}return r}return Object.setPrototypeOf(e,Object.getPrototypeOf(t)),k&&Object.defineProperty(e,k,{value:e,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(e,n(t))},e.promisify.custom=k,e.callbackify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');function e(){for(var e=[],n=0;n<arguments.length;n++)e.push(arguments[n]);var r=e.pop();if("function"!=typeof r)throw new TypeError("The last argument must be of type Function");var i=this,o=function(){return r.apply(i,arguments)};t.apply(this,e).then(function(t){process.nextTick(o,null,t)},function(t){process.nextTick(A,t,o)})}return Object.setPrototypeOf(e,Object.getPrototypeOf(t)),Object.defineProperties(e,n(t)),e}}),av=(ov.format,ov.deprecate,ov.debuglog,ov.inspect,ov.isArray,ov.isBoolean,ov.isNull,ov.isNullOrUndefined,ov.isNumber,ov.isString,ov.isSymbol,ov.isUndefined,ov.isRegExp,ov.isObject,ov.isDate,ov.isError,ov.isFunction,ov.isPrimitive);ov.isBuffer,ov.log,ov.inherits,ov._extend,ov.promisify,ov.callbackify;function sv(t,e,n,r){if(void 0===n&&(n=new Map),void 0===r&&(r=new Set),null==t)return null;if(r.has(t))throw new Error("Circular references are not supported.");if(n.has(t))return n.get(t);var i=e(t);if(i.recurse&&null!==i.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(i.recurse){if(pv(t)){var o=Array.isArray(t)?[]:{};for(var a in r.add(t),t){var s=sv(t[a],e,n,r);o[a]=s}return r.delete(t),o}throw new Error("Can't recurse into non-iterable type: "+t)}return n.set(t,i.value),i.value}function uv(t,e){return void 0===e&&(e=lv),function t(e,n,r){void 0===r&&(r=new Set);var i=e[0];if(r.has(i))throw new Error("Circular references are not supported.");var o=n(e);if(o.recurse&&null!==o.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(o.recurse){if(pv(i)){var a=Array.isArray(i)?[]:{};r.add(i);var s=function(i){var o=t(e.map(function(t){return t[i]}),n,r);a[i]=o};for(var u in i)s(u);return r.delete(i),a}throw new Error("Can't recurse into non-iterable type: "+i)}return o.value}(t,e)}function lv(t){return null===t?null:pv(t[0])?{value:null,recurse:!0}:{value:t,recurse:!1}}function cv(t,e){return Ly(this,void 0,void 0,function(){var n,r,i,o,a,s;return Fy(this,function(u){switch(u.label){case 0:n=new Map,sv(t,e,n),r=0,i=Array.from(n.keys()),u.label=1;case 1:return r<i.length?(o=i[r],(a=n.get(o))instanceof Promise?[4,a]:[3,3]):[3,4];case 2:s=u.sent(),n.set(o,s),u.label=3;case 3:return r++,[3,1];case 4:return[2,sv(t,e,n)]}})})}function pv(t){return null!=t&&(Array.isArray(t)||"object"==typeof t&&!(t instanceof lt))}var hv=function(){function t(t){if(this.capacity=t,this.begin=0,this.end=0,null==t)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(t<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(t),this.doubledCapacity=2*t}return t.prototype.wrap=function(t){for(;t<0;)t+=this.doubledCapacity;return t%this.doubledCapacity},t.prototype.get=function(t){if(t<0)throw new RangeError("Can't get item at a negative index.");return this.data[t%this.capacity]},t.prototype.set=function(t,e){if(t<0)throw new RangeError("Can't set item at a negative index.");this.data[t%this.capacity]=e},t.prototype.length=function(){var t=this.end-this.begin;return t<0&&(t=this.doubledCapacity+t),t},t.prototype.isFull=function(){return this.length()===this.capacity},t.prototype.isEmpty=function(){return 0===this.length()},t.prototype.push=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,t),this.end=this.wrap(this.end+1)},t.prototype.pushAll=function(t){for(var e=0,n=t;e<n.length;e++){var r=n[e];this.push(r)}},t.prototype.pop=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);var t=this.get(this.end);return this.set(this.end,void 0),t},t.prototype.unshift=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,t)},t.prototype.shift=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var t=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),t},t.prototype.shuffleExcise=function(t){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var e=this.wrap(this.begin+t),n=this.get(e);return this.set(e,this.pop()),n},t}(),fv=function(t){function e(){return t.call(this,e.INITIAL_CAPACITY)||this}return My(e,t),e.prototype.isFull=function(){return!1},e.prototype.push=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.push.call(this,e)},e.prototype.unshift=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.unshift.call(this,e)},e.prototype.expand=function(){for(var t=2*this.capacity,e=new Array(t),n=this.length(),r=0;r<n;r++)e[r]=this.get(this.wrap(this.begin+r));this.data=e,this.capacity=t,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n},e.INITIAL_CAPACITY=32,e}(hv);function dv(t){return new bv(t)}function mv(t){return new wv(t)}var gv,yv,vv=function(){function t(){}return t.prototype.toArray=function(){return Ly(this,void 0,void 0,function(){var t,e;return Fy(this,function(n){switch(n.label){case 0:return t=[],[4,this.next()];case 1:e=n.sent(),n.label=2;case 2:return e.done?[3,4]:(t.push(e.value),[4,this.next()]);case 3:return e=n.sent(),[3,2];case 4:return[2,t]}})})},t.prototype.toArrayForTest=function(){return Ly(this,void 0,void 0,function(){var t,e,n;return Fy(this,function(r){switch(r.label){case 0:return t=this.prefetch(100),e=[],[4,t.next()];case 1:n=r.sent(),r.label=2;case 2:return n.done?[3,4]:(e.push(n.value),[4,t.next()]);case 3:return n=r.sent(),[3,2];case 4:return[2,e]}})})},t.prototype.resolveFully=function(){return Ly(this,void 0,void 0,function(){var t;return Fy(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:t=e.sent(),e.label=2;case 2:return t.done?[3,4]:[4,this.next()];case 3:return t=e.sent(),[3,2];case 4:return[2]}})})},t.prototype.resolveWhile=function(t){return Ly(this,void 0,void 0,function(){var e,n;return Fy(this,function(r){switch(r.label){case 0:return[4,this.next()];case 1:e=r.sent(),n=t(e.value),r.label=2;case 2:return e.done||!n?[3,4]:[4,this.next()];case 3:return e=r.sent(),n=t(e.value),[3,2];case 4:return[2]}})})},t.prototype.handleErrors=function(t){return new kv(this,t)},t.prototype.filter=function(t){return new Ev(this,t)},t.prototype.map=function(t){return new Iv(this,t)},t.prototype.mapAsync=function(t){return new Av(this,t)},t.prototype.serialMapAsync=function(t){return new Av(this,t).serial()},t.prototype.flatmap=function(t){return new Rv(this,t)},t.prototype.forEachAsync=function(t){return Ly(this,void 0,void 0,function(){return Fy(this,function(e){return[2,this.map(t).resolveFully()]})})},t.prototype.serialForEach=function(t){return Ly(this,void 0,void 0,function(){return Fy(this,function(e){return[2,this.serialMapAsync(t).resolveWhile(function(t){return!0===t})]})})},t.prototype.rowMajorBatch=function(t,e){return void 0===e&&(e=!0),new Cv(this,t,e)},t.prototype.columnMajorBatch=function(t,e,n){return void 0===e&&(e=!0),void 0===n&&(n=lv),this.rowMajorBatch(t,e).map(function(t){return uv(t,n)})},t.prototype.concatenate=function(t,e){return new Dv(dv([this,t]),e)},t.prototype.take=function(t){return t<0||null==t?this:new Sv(this,t)},t.prototype.skip=function(t){return t<0||null==t?this:new Nv(this,t)},t.prototype.prefetch=function(t){return new _v(this,t)},t.prototype.shuffle=function(t,e){return new Mv(this,t,e)},t.prototype.serial=function(){return new xv(this)},t}(),bv=function(t){function e(e){var n=t.call(this)||this;return n.items=e,n.trav=0,n}return My(e,t),e.prototype.summary=function(){return"Array of "+this.items.length+" items"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t,e;return Fy(this,function(n){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(t=this.items[this.trav],e=t instanceof lt?Vo(t):t,this.trav++,[2,{value:e,done:!1}])})})},e}(vv),wv=function(t){function e(e){var n=t.call(this)||this;return n.nextFn=e,n}return My(e,t),e.prototype.summary=function(){return"Function call"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){try{return[2,this.nextFn()]}catch(t){throw t.message="Error thrown while iterating through a dataset: "+t.message,t}return[2]})})},e}(vv),xv=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.lastRead=Promise.resolve({value:null,done:!1}),n}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t=this;return Fy(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){return[2,this.upstream.next()]})})},e}(vv),Nv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t=this;return Fy(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return Ly(this,void 0,void 0,function(){var t;return Fy(this,function(e){switch(e.label){case 0:return this.count++<this.maxCount?[4,this.upstream.next()]:[3,2];case 1:return(t=e.sent()).done?[2,t]:(Kt(t.value),[3,0]);case 2:return[2,this.upstream.next()]}})})},e}(vv),Sv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Take"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},e}(vv),Cv=function(t){function e(e,n,r){void 0===r&&(r=!0);var i=t.call(this)||this;return i.upstream=e,i.batchSize=n,i.enableSmallLastBatch=r,i.lastRead=Promise.resolve({value:null,done:!1}),i}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t=this;return Fy(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return Ly(this,void 0,void 0,function(){var t,e;return Fy(this,function(n){switch(n.label){case 0:t=[],n.label=1;case 1:return t.length<this.batchSize?[4,this.upstream.next()]:[3,3];case 2:return(e=n.sent()).done?this.enableSmallLastBatch&&t.length>0?[2,{value:t,done:!1}]:[2,{value:null,done:!0}]:(t.push(e.value),[3,1]);case 3:return[2,{value:t,done:!1}]}})})},e}(vv),Ev=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.predicate=n,r.lastRead=Promise.resolve({value:null,done:!1}),r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t=this;return Fy(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return Ly(this,void 0,void 0,function(){var t;return Fy(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:return(t=e.sent()).done||this.predicate(t.value)?[2,t]:(Kt(t.value),[3,0]);case 2:return[2]}})})},e}(vv),Iv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Map"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t,e,n,r,i,o,a;return Fy(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,{value:null,done:!0}];for(e=ev(t.value),n=this.transform(t.value),r=ev(n),i=0,o=e;i<o.length;i++)a=o[i],tv(a,r)||a.dispose();return[2,{value:n,done:!1}]}})})},e}(vv),kv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.handler=n,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> handleErrors"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t=this;return Fy(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return Ly(this,void 0,void 0,function(){var t;return Fy(this,function(e){switch(e.label){case 0:e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,e.sent()];case 3:return t=e.sent(),this.handler(t)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2]}})})},e}(vv),Av=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t,e,n,r,i,o,a;return Fy(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:return(t=s.sent()).done?[2,{value:null,done:!0}]:(e=ev(t.value),[4,this.transform(t.value)]);case 2:for(n=s.sent(),r=ev(n),i=0,o=e;i<o.length;i++)a=o[i],tv(a,r)||a.dispose();return[2,{value:n,done:!1}]}})})},e}(vv),Tv=function(t){function e(){var e=t.call(this)||this;return e.outputQueue=new fv,e.lastRead=Promise.resolve({value:null,done:!1}),e}return My(e,t),e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t=this;return Fy(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){switch(t.label){case 0:return 0!==this.outputQueue.length()?[3,2]:[4,this.pump()];case 1:return t.sent()?[3,0]:[2,{value:null,done:!0}];case 2:return[2,{value:this.outputQueue.shift(),done:!1}]}})})},e}(vv),Rv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Flatmap"},e.prototype.pump=function(){return Ly(this,void 0,void 0,function(){var t,e,n,r,i,o,a;return Fy(this,function(s){switch(s.label){case 0:return[4,this.upstream.next()];case 1:if((t=s.sent()).done)return[2,!1];for(e=ev(t.value),n=this.transform(t.value),r=ev(n),this.outputQueue.pushAll(n),i=0,o=e;i<o.length;i++)a=o[i],tv(a,r)||a.dispose();return[2,!0]}})})},e}(Tv),Dv=function(t){function e(e,n){var r=t.call(this)||this;return r.baseErrorHandler=n,r.lastRead=null,r.iterator=null,r.moreIterators=e,r}return My(e,t),e.prototype.summary=function(){return"TODO: fill in upstream of chained summaries -> Chained"},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},e.prototype.readFromChain=function(t){return Ly(this,void 0,void 0,function(){var e,n;return Fy(this,function(r){switch(r.label){case 0:return[4,t];case 1:return r.sent(),null!=this.iterator?[3,3]:[4,this.moreIterators.next()];case 2:if((e=r.sent()).done)return[2,{value:null,done:!0}];this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),r.label=3;case 3:return[4,this.iterator.next()];case 4:return(n=r.sent()).done?(this.iterator=null,[2,this.readFromChain(t)]):[2,n]}})})},e}(vv);(yv=gv||(gv={}))[yv.FAIL=0]="FAIL",yv[yv.SHORTEST=1]="SHORTEST",yv[yv.LONGEST=2]="LONGEST";var Ov=function(t){function e(e,n){void 0===n&&(n=gv.FAIL);var r=t.call(this)||this;return r.iterators=e,r.mismatchMode=n,r.count=0,r.currentPromise=null,r}return My(e,t),e.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},e.prototype.nextState=function(t){return Ly(this,void 0,void 0,function(){function e(t){return t instanceof vv?{value:t.next().then(function(t){return n++,t.done&&r++,t.value}),recurse:!1}:{value:null,recurse:!0}}var n,r,i;return Fy(this,function(o){switch(o.label){case 0:return[4,t];case 1:return o.sent(),n=0,r=0,[4,cv(this.iterators,e)];case 2:if(i=o.sent(),n===r)return[2,{value:null,done:!0}];if(r>0)switch(this.mismatchMode){case gv.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case gv.SHORTEST:return[2,{value:null,done:!0}];case gv.LONGEST:}return this.count++,[2,{value:i,done:!1}]}})})},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){switch(t.label){case 0:return this.currentPromise=this.nextState(this.currentPromise),[4,this.currentPromise];case 1:return[2,t.sent()]}})})},e}(vv),_v=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.bufferSize=n,r.buffer=new hv(n),r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},e.prototype.refill=function(){for(;!this.buffer.isFull();){var t=this.upstream.next();this.buffer.push(t)}},e.prototype.next=function(){return this.refill(),this.buffer.shift()},e}(vv),Mv=function(t){function e(e,n,r){var i=t.call(this,e,n)||this;return i.upstream=e,i.windowSize=n,i.upstreamExhausted=!1,i.random=Ky(r||X.now().toString()),i.lastRead=Promise.resolve({value:null,done:!1}),i}return My(e,t),e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t=this;return Fy(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.randomInt=function(t){return Math.floor(this.random()*t)},e.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},e.prototype.serialNext=function(){return Ly(this,void 0,void 0,function(){var t,e;return Fy(this,function(n){switch(n.label){case 0:this.upstreamExhausted||this.refill(),n.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(t=this.chooseIndex(),[4,this.buffer.shuffleExcise(t)]);case 2:return(e=n.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,e]);case 3:return[2,{value:null,done:!0}]}})})},e}(_v),Lv=function(){function t(){this.size=null}return t.prototype.batch=function(t,e){var n=this;void 0===e&&(e=!0);var r=this;return X.assert(t>0,function(){return"batchSize needs to be positive, but it is\n      "+t}),Fv(function(){return Ly(n,void 0,void 0,function(){return Fy(this,function(n){switch(n.label){case 0:return[4,r.iterator()];case 1:return[2,n.sent().columnMajorBatch(t,e,zv)]}})})},this.size===1/0||null==this.size?this.size:e?Math.ceil(this.size/t):Math.floor(this.size/t))},t.prototype.concatenate=function(t){var e=this,n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){var e,r;return Fy(this,function(i){switch(i.label){case 0:return[4,n.iterator()];case 1:return r=(e=i.sent()).concatenate,[4,t.iterator()];case 2:return[2,r.apply(e,[i.sent()])]}})})},this.size===1/0||t.size===1/0?1/0:null!=this.size&&null!=t.size?this.size+t.size:null)},t.prototype.filter=function(t){var e=this,n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().filter(function(e){return Gt(function(){return t(e)})})]}})})},this.size===1/0?1/0:null)},t.prototype.forEachAsync=function(t){return Ly(this,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().forEachAsync(t)]}})})},t.prototype.forEach=function(t){return Ly(this,void 0,void 0,function(){return Fy(this,function(e){return Bt("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(t)]})})},t.prototype.map=function(t){var e=this,n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().map(function(e){return Gt(function(){return t(e)})})]}})})},this.size)},t.prototype.mapAsync=function(t){var e=this,n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().mapAsync(t)]}})})},this.size)},t.prototype.prefetch=function(t){var e=this;if(null==t)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().prefetch(t)]}})})},this.size)},t.prototype.repeat=function(t){var e=this,n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){var e=this;return Fy(this,function(r){return[2,function(t,e){return new Dv(t,e)}(mv(function(){return Ly(e,void 0,void 0,function(){var t;return Fy(this,function(e){switch(e.label){case 0:return t={},[4,n.iterator()];case 1:return[2,(t.value=e.sent(),t.done=!1,t)]}})})}).take(t))]})})},null!=this.size&&t>0?this.size*t:0===t?0:null!=this.size&&(void 0===t||t<0)?1/0:null)},t.prototype.skip=function(t){var e=this,n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().skip(t)]}})})},null!=this.size&&t>=0&&this.size>=t?this.size-t:null!=this.size&&(this.size<t||void 0===t||t<0)?0:null)},t.prototype.shuffle=function(t,e,n){var r=this;if(void 0===n&&(n=!0),null==t||t<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.  If your data fits in main memory (for regular JS objects), and/or GPU memory (for `tf.Tensor`s), consider setting bufferSize to the dataset size ("+this.size+" elements)");var i=this,o=Ky(e||X.now().toString());return Fv(function(){return Ly(r,void 0,void 0,function(){var e;return Fy(this,function(r){switch(r.label){case 0:return e=o.int32(),n&&(e+=o.int32()),[4,i.iterator()];case 1:return[2,r.sent().shuffle(t,e.toString())]}})})},this.size)},t.prototype.take=function(t){var e=this,n=this;return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().take(t)]}})})},null!=this.size&&this.size>t?t:null!=this.size&&this.size<=t?this.size:null)},t.prototype.toArray=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArray()]}})})},t.prototype.toArrayForTest=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArrayForTest()]}})})},t.MAX_BUFFER_SIZE=1e4,t}();function Fv(t,e){return void 0===e&&(e=null),new(function(n){function r(){var t=null!==n&&n.apply(this,arguments)||this;return t.size=e,t}return My(r,n),r.prototype.iterator=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(e){return[2,t()]})})},r}(Lv))}function zv(t){return null===t?null:function(t){return null==t||av(t)||Array.isArray(t)||"object"==typeof t&&t instanceof lt||Xy(t)}(t[0])?{value:function(t){if(0===t.length)throw new Error("Can't make a batch of zero elements.");return t[0]instanceof lt?aa(t):Re(t)}(t),recurse:!1}:{value:null,recurse:!0}}var Pv=function(t){function e(e){var n=t.call(this)||this;return n.input=e,n}return My(e,t),e.prototype.iterator=function(){return Ly(this,void 0,void 0,function(){var t;return Fy(this,function(e){switch(e.label){case 0:return[4,this.input.iterator()];case 1:return t=e.sent(),[2,t.decodeUTF8().split("\n")]}})})},e}(Lv),Bv=Symbol("out"),Uv=Symbol("field"),Wv=Symbol("quote"),Vv=Symbol("quoteafterquote"),jv=Symbol("quoteinquote"),qv=function(t){function e(e,n){var r=t.call(this)||this;return r.input=e,r.hasHeader=!0,r.fullColumnNames=null,r.columnNamesValidated=!1,r.columnConfigs=null,r.configuredColumnsOnly=!1,r.delimiter=",",r.base=new Pv(e),n||(n={}),r.hasHeader=!1!==n.hasHeader,r.fullColumnNames=n.columnNames,r.columnConfigs=n.columnConfigs,r.configuredColumnsOnly=n.configuredColumnsOnly,r.delimiter=n.delimiter?n.delimiter:",",r}return My(e,t),e.prototype.columnNames=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){switch(t.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:t.sent(),t.label=2;case 2:return[2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames]}})})},e.prototype.setColumnNames=function(){return Ly(this,void 0,void 0,function(){var t,e,n,r,i,o,a=this;return Fy(this,function(s){switch(s.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(t=s.sent(),!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&t&&X.assert(t.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+a.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=t),e=this.fullColumnNames.reduce(function(t,e){return t[e]=t[e]+1||1,t},{}),n=Object.keys(e).filter(function(t){return e[t]>1}),X.assert(0===n.length,function(){return"Duplicate column names found: "+n.toString()}),this.columnConfigs)for(r=0,i=Object.keys(this.columnConfigs);r<i.length;r++)if(o=i[r],-1===this.fullColumnNames.indexOf(o))throw new Error('The key "'+o+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").");return this.columnNamesValidated=!0,[2]}})})},e.prototype.maybeReadHeaderLine=function(){return Ly(this,void 0,void 0,function(){var t;return Fy(this,function(e){switch(e.label){case 0:return this.hasHeader?[4,this.base.iterator()]:[3,3];case 1:return[4,e.sent().next()];case 2:if((t=e.sent()).done)throw new Error("No data was found for CSV parsing.");return[2,t.value.split(this.delimiter)];case 3:return[2,null]}})})},e.prototype.iterator=function(){return Ly(this,void 0,void 0,function(){var t,e=this;return Fy(this,function(n){switch(n.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:n.sent(),n.label=2;case 2:return[4,this.base.iterator()];case 3:return t=n.sent(),this.hasHeader&&(t=t.skip(1)),[2,t.map(function(t){return e.makeDataElement(t)})]}})})},e.prototype.makeDataElement=function(t){for(var e=this.parseRow(t),n={},r={},i=0;i<this.fullColumnNames.length;i++){var o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(!this.configuredColumnsOnly||a){var s=e[i],u=null;if(""===s)if(a&&void 0!==a.default)u=a.default;else{if(a&&(a.required||a.isLabel))throw new Error("Required column "+o+" is empty in this line: "+t);u=void 0}else{var l=Number(s);if(isNaN(l))u=a&&"bool"===a.dtype?this.getBoolean(s):s;else if(a&&a.dtype)switch(a.dtype){case"float32":u=l;break;case"int32":u=Math.floor(l);break;case"bool":u=this.getBoolean(s);break;default:u=l}else u=l}a&&a.isLabel?r[o]=u:n[o]=u}}return 0===Object.keys(r).length?n:{xs:n,ys:r}},e.prototype.getBoolean=function(t){return"1"===t||"true"===t.toLowerCase()?1:0},e.prototype.parseRow=function(t){for(var e=[],n=0,r=t.length,i=Uv,o=0;o<r;o++)switch(i){case Bv:switch(t.charAt(o)){case'"':n=o+1,i=Wv;break;case this.delimiter:e.push(""),i=Bv,n=o+1;break;default:i=Uv,n=o}break;case Uv:switch(t.charAt(o)){case this.delimiter:e.push(t.substring(n,o)),i=Bv,n=o+1}break;case Wv:switch(t.charAt(o)){case'"':i=Vv}break;case Vv:switch(t.charAt(o)){case this.delimiter:e.push(t.substring(n,o-1)),i=Bv,n=o+1;break;case'"':i=Wv;break;default:i=jv}break;case jv:switch(t.charAt(o)){case'"':i=Wv}}return i===Vv?e.push(t.substring(n,r-1)):e.push(t.substring(n)),e},e}(Lv),Gv=function(){},Hv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return My(e,t),e.prototype.split=function(t){return new Kv(this,t)},e}(vv),Kv=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.impl=new $v(e,n),r}return My(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){return[2,this.impl.next()]})})},e}(Hv),$v=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.separator=n,r.carryover="",r}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},e.prototype.pump=function(){return Ly(this,void 0,void 0,function(){var t,e,n,r,i;return Fy(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:if((t=o.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((e=t.value.split(this.separator))[0]=this.carryover+e[0],n=0,r=e.slice(0,-1);n<r.length;n++)i=r[n],this.outputQueue.push(i);return this.carryover=e[e.length-1],[2,!0]}})})},e}(Tv),Xv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return My(e,t),e.prototype.decodeUTF8=function(){return new Yv(this)},e}(vv),Yv=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.impl=new Jv(e),n}return My(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){return[2,this.impl.next()]})})},e}(Hv),Jv=function(t){function e(e){var n=t.call(this)||this;if(n.upstream=e,Ut.get("IS_BROWSER"))n.decoder=new TextDecoder("utf-8");else{var r=require("string_decoder").StringDecoder;n.decoder=new r("utf8")}return n}return My(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Utf8"},e.prototype.pump=function(){return Ly(this,void 0,void 0,function(){var t,e,n;return Fy(this,function(r){switch(r.label){case 0:return[4,this.upstream.next()];case 1:return(t=r.sent()).done?[2,!1]:(e=t.value,n=Ut.get("IS_BROWSER")?this.decoder.decode(e,{stream:!0}):this.decoder.write(Buffer.from(e.buffer)),this.outputQueue.push(n),[2,!0])}})})},e}(Tv),Zv=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.file=e,r.options=n,X.assert(e instanceof Uint8Array||!!Ut.get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."}),r.offset=n.offset||0,r.chunkSize=n.chunkSize||1048576,r}return My(e,t),e.prototype.summary=function(){return"FileChunks "+this.file},e.prototype.next=function(){return Ly(this,void 0,void 0,function(){var t,e,n=this;return Fy(this,function(r){switch(r.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(t=new Promise(function(t,e){var r=n.offset+n.chunkSize;if(n.file instanceof Uint8Array)t(new Uint8Array(n.file.slice(n.offset,r)));else{var i=new FileReader;i.onload=function(n){var r=i.result;if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),!(r instanceof Uint8Array))return e(new TypeError("FileReader returned unknown type."));t(r)},i.onabort=function(t){return e(new Error("Aborted"))},i.onerror=function(t){return e(new Error(t.type))};var o=n.file.slice(n.offset,r);i.readAsArrayBuffer(o)}n.offset=r}),e={},[4,t]);case 1:return[2,(e.value=r.sent(),e.done=!1,e)]}})})},e}(Xv);function Qv(t){return"string"==typeof t&&"file://"===t.substr(0,7)}var tb=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.input=e,r.options=n,r}return My(e,t),e.prototype.iterator=function(){return Ly(this,void 0,void 0,function(){var t;return Fy(this,function(e){return Qv(this.input)&&Ut.get("IS_NODE")&&(t=require("fs"),this.input=t.readFileSync(this.input.substr(7))),[2,new Zv(this.input,this.options)]})})},e}(Gv),eb=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.url=e,r.fileOptions=n,r}return My(e,t),e.prototype.iterator=function(){return Ly(this,void 0,void 0,function(){return Fy(this,function(t){return Qv(this.url)?[2,new tb(this.url,this.fileOptions).iterator()]:[2,function(t,e){return void 0===e&&(e={}),Ly(this,void 0,void 0,function(){var n,r,i,o;return Fy(this,function(a){switch(a.label){case 0:return Ut.get("IS_BROWSER")?[4,fetch(t)]:[3,5];case 1:return(n=a.sent()).ok?[4,n.blob()]:[3,3];case 2:return r=a.sent(),[2,new Zv(r,e)];case 3:throw new Error(n.statusText);case 4:return[3,9];case 5:if(i=require("node-fetch"),"string"!=typeof t)throw new Error("URL must be a string. Request objects are not supported in the node.js environment yet.");return[4,i(t)];case 6:return(n=a.sent()).ok?[4,n.buffer()]:[3,8];case 7:return o=a.sent(),[2,new Zv(o,e)];case 8:throw new Error(n.statusText);case 9:return[2]}})})}(this.url,this.fileOptions)]})})},e}(Gv);var nb=Object.freeze({array:function(t){var e=this;return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(e){return[2,dv(t)]})})},t.length)},Dataset:Lv,zip:function(t){var e,n=this;if(!pv(t))throw new Error("The argument to zip() must be an object or array.");if(Array.isArray(t))for(var r=0;r<t.length;r++)e=null==e?t[r].size:Math.min(e,t[r].size);else if(t instanceof Object)for(var i in t)e=null==e?t[i].size:Math.min(e,t[i].size);return Fv(function(){return Ly(n,void 0,void 0,function(){return Fy(this,function(e){switch(e.label){case 0:return[4,cv(t,function(t){if(t instanceof Lv)return{value:t.iterator(),recurse:!1};if(pv(t))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})];case 1:return[2,function(t,e){return void 0===e&&(e=gv.FAIL),new Ov(t,e)}(e.sent(),gv.SHORTEST)]}})})},e)},CSVDataset:qv,TextLineDataset:Pv,csv:function(t,e){return void 0===e&&(e={}),new qv(new eb(t),e)},func:function(t){var e=this,n=mv(t);return Fv(function(){return Ly(e,void 0,void 0,function(){return Fy(this,function(t){return[2,n]})})})},generator:function(t){var e=this;return Fv(function(){return Ly(e,void 0,void 0,function(){var e;return Fy(this,function(n){switch(n.label){case 0:return[4,t()];case 1:return e=n.sent(),[2,mv(function(){return e.next()})]}})})})},FileDataSource:tb,URLDataSource:eb,version_data:"1.0.1"}),rb={"tfjs-core":"1.0.1","tfjs-data":"1.0.1","tfjs-layers":"1.0.1","tfjs-converter":"1.0.1",tfjs:"1.0.1"};t.data=nb,t.version=rb,t.setBackend=Qc,t.getBackend=tp,t.disposeVariables=ep,t.memory=np,t.version_core="1.0.1",t.nextFrame=zl,t.enableProdMode=Ft,t.enableDebugMode=zt,t.disableDeprecationWarnings=Pt,t.deprecationWarn=Bt,t.browser=_c,t.environment=Wt,t.io=Tc,t.math=Dc,t.serialization=zc,t.test_util=Wc,t.util=X,t.webgl=Vc,t.AdadeltaOptimizer=qc,t.AdagradOptimizer=Gc,t.AdamOptimizer=Hc,t.AdamaxOptimizer=Kc,t.MomentumOptimizer=Xc,t.Optimizer=jc,t.RMSPropOptimizer=Yc,t.SGDOptimizer=$c,t.Tensor=lt,t.TensorBuffer=ot,t.variable=gt,t.Variable=ct,t.ENV=Ut,t.Environment=Mt,t.KernelBackend=He,t.DataStorage=Ge,t.image=Dl,t.linalg=Cl,t.losses=wl,t.spectral=ul,t.fused=_l,t.op=Ce,t.batchNormalization2d=Za,t.batchNormalization3d=Qa,t.batchNormalization4d=ts,t.batchNormalization=es,t.batchNorm=ns,t.batchNorm2d=rs,t.batchNorm3d=is,t.batchNorm4d=os,t.complex=ke,t.real=Ae,t.imag=Te,t.concat=No,t.concat1d=So,t.concat2d=Co,t.concat3d=Eo,t.concat4d=Io,t.split=ko,t.conv1d=vs,t.conv2d=bs,t.conv3d=ws,t.conv2dDerFilter=xs,t.depthwiseConv2d=Ns,t.separableConv2d=Ss,t.conv2dTranspose=Cs,t.matMul=Es,t.dot=Is,t.outerProduct=ks,t.reverse=As,t.reverse1d=Ts,t.reverse2d=Rs,t.reverse3d=Ds,t.reverse4d=Os,t.maxPool=Ls,t.avgPool=Fs,t.pool=zs,t.slice=Ps,t.slice1d=Bs,t.slice2d=Us,t.slice3d=Ws,t.slice4d=Vs,t.abs=da,t.acos=ma,t.acosh=ga,t.asin=ya,t.asinh=va,t.atan=ba,t.atanh=wa,t.ceil=xa,t.clipByValue=Na,t.cos=Sa,t.cosh=Ca,t.erf=Ea,t.exp=Ia,t.expm1=ka,t.floor=Aa,t.log=Ta,t.log1p=Ra,t.logSigmoid=Da,t.neg=Oa,t.reciprocal=_a,t.round=Ma,t.rsqrt=La,t.sigmoid=Fa,t.sign=za,t.sin=Pa,t.sinh=Ba,t.softplus=Ua,t.sqrt=Wa,t.square=Va,t.step=ja,t.tan=qa,t.tanh=Ga,t.all=qs,t.any=Gs,t.argMax=Hs,t.argMin=Ks,t.logSumExp=$s,t.max=Xs,t.mean=Ys,t.min=Js,t.moments=Zs,t.sum=Qs,t.prod=tu,t.equal=eu,t.equalStrict=nu,t.greater=ru,t.greaterEqual=iu,t.greaterEqualStrict=ou,t.greaterStrict=au,t.less=su,t.lessEqual=uu,t.lessEqualStrict=lu,t.lessStrict=cu,t.notEqual=pu,t.notEqualStrict=hu,t.add=fu,t.addN=du,t.addStrict=mu,t.atan2=gu,t.div=yu,t.divStrict=vu,t.floorDiv=bu,t.maximum=wu,t.maximumStrict=xu,t.minimum=Nu,t.minimumStrict=Su,t.mod=Cu,t.modStrict=Eu,t.mul=Iu,t.mulStrict=ku,t.pow=Au,t.powStrict=Tu,t.squaredDifference=Ru,t.squaredDifferenceStrict=Du,t.sub=Ou,t.subStrict=_u,t.elu=Uu,t.leakyRelu=Wu,t.prelu=Vu,t.relu=ju,t.selu=qu,t.logicalAnd=Mu,t.logicalNot=Lu,t.logicalOr=Fu,t.logicalXor=zu,t.where=Pu,t.whereAsync=Bu,t.buffer=Po,t.print=Bo,t.batchToSpaceND=Uo,t.cast=Wo,t.clone=Vo,t.cumsum=jo,t.depthToSpace=qo,t.expandDims=Go,t.eye=Ho,t.multinomial=Ko,t.oneHot=$o,t.pad=Xo,t.pad1d=Yo,t.pad2d=Jo,t.pad3d=Zo,t.pad4d=Qo,t.rand=ta,t.randomNormal=ea,t.randomUniform=na,t.reshape=ra,t.spaceToBatchND=ia,t.squeeze=oa,t.stack=aa,t.tile=sa,t.truncatedNormal=ua,t.unstack=la,t.setdiff1dAsync=ca,t.fill=Ue,t.linspace=We,t.ones=Pe,t.range=Ve,t.scalar=De,t.tensor=Re,t.tensor1d=Oe,t.tensor2d=_e,t.tensor3d=Me,t.tensor4d=Le,t.tensor5d=Fe,t.tensor6d=ze,t.zeros=Be,t.onesLike=je,t.zerosLike=qe,t.transpose=Gu,t.softmax=Ee,t.logSoftmax=Ie,t.localResponseNormalization=Hu,t.norm=Ku,t.gather=Yu,t.unsortedSegmentSum=Ju,t.basicLSTMCell=Zu,t.multiRNNCell=Qu,t.movingAverage=tl,t.stridedSlice=el,t.topk=nl,t.scatterND=rl,t.fft=il,t.ifft=ol,t.rfft=al,t.irfft=sl,t.sparseToDense=ll,t.gatherND=cl,t.train=Zc,t.tidy=Gt,t.keep=Ht,t.dispose=Kt,t.time=$t,t.profile=Xt,t.customGrad=jt,t.grad=function(t){return d(U(t),function(){return"The f passed in grad(f) must be a function"}),function(e,n){return d(e instanceof lt,function(){return"The x passed in grad(f)(x) must be a tensor"}),d(null==n||n instanceof lt,function(){return"The dy passed in grad(f)(x, dy) must be a tensor"}),Ut.engine.tidy(function(){var r=Ut.engine.gradients(function(){return t(e)},[e],n),i=r.value,o=r.grads;return null!=n&&m(i.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),qt(o),o[0]})}},t.grads=function(t){return d(U(t),function(){return"The f passed in grads(f) must be a function"}),function(e,n){return d(Array.isArray(e)&&e.every(function(t){return t instanceof lt}),function(){return"The args passed in grads(f)(args) must be an array of tensors"}),d(null==n||n instanceof lt,function(){return"The dy passed in grads(f)(args, dy) must be a tensor"}),Ut.engine.tidy(function(){var r=Ut.engine.gradients(function(){return t.apply(void 0,e)},e,n),i=r.value,o=r.grads;return null!=n&&m(i.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),qt(o),o})}},t.valueAndGrad=function(t){return d(U(t),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(e,n){d(e instanceof lt,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),d(null==n||n instanceof lt,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var r=Ut.engine.gradients(function(){return t(e)},[e],n),i=r.grads,o=r.value;return qt(i),{grad:i[0],value:o}}},t.valueAndGrads=function(t){return d(U(t),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(e,n){d(Array.isArray(e)&&e.every(function(t){return t instanceof lt}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),d(null==n||n instanceof lt,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var r=Ut.engine.gradients(function(){return t.apply(void 0,e)},e,n);return null!=n&&m(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),qt(r.grads),r}},t.variableGrads=Vt,t.constraints=$p,t.initializers=Zh,t.layers=Og,t.metrics=_g,t.models=Mg,t.regularizers=Fg,t.CallbackList=xf,t.CustomCallback=Ef,t.History=Cf,t.Callback=zg,t.InputSpec=lf,t.SymbolicTensor=cf,t.LayersModel=Fd,t.input=Bd,t.loadLayersModel=function(t,e){return null==e&&(e={}),zd(t,e)},t.model=function(t){return new Fd(t)},t.registerCallbackConstructor=function(t,e){kf.registerCallbackConstructor(t,e)},t.sequential=function(t){return new Pd(t)},t.RNN=ug,t.Sequential=Pd,t.LayerVariable=af,t.version_layers="1.0.1",t.GraphModel=Oy,t.loadGraphModel=function(t,e){return void 0===e&&(e={}),Bg(this,void 0,void 0,function(){var n;return Ug(this,function(r){switch(r.label){case 0:if(null==t)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==e&&(e={}),e.fromTFHub&&null==t.load&&(t.endsWith("/")||(t+="/"),t=""+t+Dy+Ry),[4,(n=new Oy(t,e)).load()];case 1:return r.sent(),[2,n]}})})},t.version_converter="1.0.1",Object.defineProperty(t,"__esModule",{value:!0})});
//# sourceMappingURL=tf.min.js.map
